BINARY-SEARCH(A, key, start, end)
Input: A an ordered array from 0 to A.size()-1
key an element of the type stored in the array
start the first position in the array to be searched
end the last position in the array to be searched
Output: A boolean indicating that key is in A (true) or not (false)
Note, we could also return the position of A if we wished.
- if start > end
- return false
- mid ← (start+end)/2
- if A[mid] = key
- return true
- else if A[mid] < key
- return BinarySearch(A, key, mid+1, end)
- else
- return BinarySearch(A, key, start, mid-1)
Prove the base case 1: end - start ≤ 0
A binary search on an array of size 0 will return the correct value
By this case, it is not in the array, so by line 2, false will be returned.
Base Case 2: end-start = 1
A binary search on an array of size 1 will return the correct value
If it is in the array, it will be located at the one position in the array
This will be mid (line 3) ,
and that is checked in line 4-5 and true will be returned
If it is not in the array, either line 7 or line 9 will be called
In either case, false will be returned by above.
Assume true for k > 1
A binary search of an array of size k will return the correct value.
Prove true for k+1
If the element is at the middle of the array,
the correct value will be returned by line 4-5
If it is not at the middle of the array,
an array of size (k+1)/2 will be searched in line 7 or 9.
These are of size ≤ k, therefore by induction they must
return the correct value
Thus binary search on an array of size k+1 must
return the correct value.