Skip to content

Commit f6e3649

Browse files
author
Hieu Luong
committed
General binary search approach
1 parent a458ec6 commit f6e3649

File tree

1 file changed

+37
-47
lines changed

1 file changed

+37
-47
lines changed

src/binarysearch/ReadMe.java

Lines changed: 37 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2,53 +2,43 @@
22

33
public class ReadMe {
44

5-
/**
6-
* summary of 2 most frequently used binary search templates.
7-
* one is return index during the search:
8-
*
9-
* while lo <= hi:
10-
* mid = (lo+hi)/2
11-
* if nums[mid] == target:
12-
* return mid
13-
* if nums[mid] > target:
14-
* hi = mid-1
15-
* else:
16-
* lo = mid+1
17-
* return -1
18-
*
19-
* Another more frequently used binary search template is for searching lowest element
20-
* satisfy function(i) == True (the array should satisfy function(x) == False for 0 to i-1,
21-
* and function(x) == True for i to n-1, and it is up to the question to define the function,
22-
* like in the find peak element problem, function(x) can be nums[x] < nums[x+1] ),
23-
* there are 2 ways to write it:
24-
*
25-
* while lo <= hi:
26-
* mid = (lo+hi)/2
27-
* if function(mid):
28-
* hi = mid-1
29-
* else:
30-
* lo = mid+1
31-
* return lo
32-
*
33-
* or
34-
*
35-
* while lo < hi:
36-
* mid = (lo+hi)/2
37-
* if function(mid):
38-
* hi = mid
39-
* else:
40-
* lo = mid+1
41-
*
42-
* return lo ---> lowest element that satifies function(x)
43-
* return hi ---> highest element that not satifies function(x)
44-
*
45-
* No matter which one you use, just be careful about updating the hi and lo,
46-
* which could easily lead to infinite loop.
47-
* Some binary question is searching a floating number
48-
* and normally the question will give you a precision,
49-
* in which case you don't need to worry too much about the infinite loop
50-
* but your while condition will become something like "while lo+1e-7<hi"
51-
*
5+
/*
6+
|--x-----x------[v]vvvvvvvvvvvvvvvv|
7+
while (lo <= hi) {
8+
int mid = lo + (hi-lo)/2;
9+
if function(mid)
10+
hi = mid-1;
11+
else
12+
lo = mid+1;
13+
}
14+
return lo; ---> lowest element that satisfies function(x)
15+
16+
|vvvvvvvvvvvvv[v]-----x------x-------|
17+
while (lo <= hi) {
18+
int mid = lo + (hi-lo)/2;
19+
if function(mid)
20+
lo = mid+1;
21+
else
22+
hi = mid-1;
23+
}
24+
return hi; ---> highest element that satisfies function(x)
25+
26+
|----x----[v]----------x--------------|
27+
while (lo <= hi) {
28+
int mid = lo + (hi-lo)/2;
29+
if function(mid) == target
30+
return mid;
31+
if function(mid) < target
32+
lo = mid+1;
33+
else
34+
hi = mid-1;
35+
}
36+
return -1;
37+
38+
Note: function(x) is non-decreasing function
39+
*/
40+
41+
/*
5242
*
5343
* Collections.binarySearch
5444
* Array.binarySearch

0 commit comments

Comments
 (0)