Binary Search is a classical optimal search algorithm:
Look at the middle element of an array.
If the number you're searching is larger than the middle element, search the upper half.
If the number you're searching is smaller than the middle element, search the lower half.
Otherwise, the number is found.
- Apply the two questions for constructing a recursive solution to Binary Search:
- Outline the an algorithm for a recursive Sequential Search and a recursive Binary Search
- Write the code for recursive Sequential Search and recursive Binary Search
- Discuss with your neighbor(s) the Big-Ohs of Sequential Search and Binary Search:
To calculate the worst-case Big-Oh for Binary Search for an array of size n consider the following:
After 1 iteration, there are n/2 elements left to search.
After 2 iterations, there are n/2/2 (or n/22) elements left to search.
After 3 iterations, there are n/2/2/2 (or n/23) elements left to search.
After 4 iterations, there are n/2/2/2/2 (or n/24) elements left to search.
After k iterations, there are n/2k elements left to search.
In the worst case, searching stops when there is 1 element left to search, so n/2k = 1
Rearranging the equation: 2k = n
Taking the log of both sides: log2 2k = log2 n
Simplifying: k log2 2 = log2 n
Simplifying: k = log2 n