Binary Search
Binary Search
Binary search
binary search: Locates a target value in a sorted
array/list by successively eliminating half of the array from
consideration.
How many elements will it need to examine? O(log N)
Can be implemented with a loop or recursively
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 2 7 10 15 20 22 25 30 36 42 50 56 68 85 92 103
2
Binary search code
// Returns the index of an occurrence of target in a,
// or a negative number if the target is not found.
// Precondition: elements of a are in sorted order
public static int binarySearch(int[] a, int target) {
int min = 0;
int max = a.length - 1;
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
value -4 2 7 10 15 20 22 25 30 36 42 50 56 68 85 92 103
4
Exercise solution
// Returns the index of an occurrence of the given value in
// the given array, or a negative number if not found.
// Precondition: elements of a are in sorted order
public static int binarySearch(int[] a, int target) {
return binarySearch(a, target, 0, a.length - 1);
}
3 6 7 11 32 33 53
6
Binary Search
3 6 7 11 32 33 53
7
Binary Search
3 6 7 11 32 33 53
8
Binary Search
3 6 7 11 32 33 53
9
Binary Search
3 6 7 11 32 33 53
10
Binary Search
3 6 7 11 32 33 53
11
Binary Search
3 6 7 11 32 33 53
12
Binary Search
3 6 7 11 32 33 53
13
Binary Search
3 6 7 11 32 33 53
14
Binary Search
3 6 7 11 32 33 53
15
Binary Search
3 6 7 11 32 33 53
16
Relation to Binary Search Tree
11
6 33
3 7 32 53
17
Search for target = 7
Find midpoint:
3 6 7 11 32 33 53
Start at root:
11
6 33
3 7 32 53
18
Search for target = 7
Search left subarray:
3 6 7 11 32 33 53
3 7 32 53
19
Search for target = 7
Find approximate midpoint of
subarray:
3 6 7 11 32 33 53
3 7 32 53
20
Search for target = 7
Search right subarray:
3 6 7 11 32 33 53
3 7 32 53
21
Binary Search: Analysis
Best Case: O(1)
Worst case complexity?
What is the maximum depth of recursive calls in binary
search as function of n?
Each level in the recursion, we split the array in half (divide
by two).
Therefore maximum recursion depth is floor(log2n) and
worst case = O(log2n).
Average case is also = O(log2n).
22