Skip to content

Commit 0fe4300

Browse files
Initial commit -Alpha Edition-
1 parent b7bdcae commit 0fe4300

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

BinarySearch.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
What else?
2+
-BinarySearch in Integer Domain.
3+
-BinarySearch in Real Domain.
4+
5+
Terminology:
6+
Search Space
7+
low
8+
high
9+
median
10+
Check function
11+
12+
You can solve the problem using BinarySearch if and only if:
13+
- You can design a check function whose domain is the problem's search space
14+
and its range is separated into at most one "False" segment and one "True" segment.
15+
16+
17+
Can you design the upper_bound function?
18+
19+
bool isGreater(int a, int b){
20+
return a > b;
21+
}
22+
23+
int upperBound(int *A, int val){
24+
int lo = 0, med, hi = n-1;
25+
while(lo<hi){
26+
mid = (lo+hi)>>1;
27+
if(isGreater(A[med], val)) hi = mid;
28+
else lo = med+1;
29+
}
30+
return lo;
31+
}
32+
33+
34+
We have two cases:
35+
1- Minimization Problems:
36+
-FFFFFFFFFFFFFFFFFFFTTTTTTTTTTTTTTTT
37+
-the range is separated into False-True range.
38+
-the target is the first True
39+
-We ceil the low and floor the median.
40+
41+
bool ok(int val){
42+
//Some Checking Statements
43+
}
44+
45+
int binarySearch(){
46+
int lo = 0, med, hi = 1000000000;
47+
while(lo<hi){
48+
mid = (lo+hi)>>1;
49+
if(ok(A[med])) hi = med;
50+
else lo = med+1;
51+
}
52+
return hi;
53+
}
54+
55+
2- Maximization Problems:
56+
-TTTTTTTTTTTTTTTFFFFFFFFFFFFFFF
57+
-the range is separated into True-False range.
58+
-the target is the last True.
59+
-We ceil the median and floor the high.
60+
61+
bool ok(int val){
62+
//Some Checking Statements
63+
}
64+
65+
int binarySearch(){
66+
int lo = 0, med, hi = 1000000000;
67+
while(lo<hi){
68+
mid = (lo+hi+1)>>1;
69+
if(ok(A[med])) lo = med;
70+
else hi = med-1;
71+
}
72+
return lo;
73+
}

0 commit comments

Comments
 (0)