Searching in a list
Naive Approach
- Scan the whole list for the element required.
- Worst case is when the element is not present in the list.
- Worst case time complexity is \(O(n)\), where \(n\) is the size of the input list.
Binary Search Approach
- The only condition for binary search is that the list should be sorted.
Approach
- Let
k
be the element to be searched and the list to be sorted in ascending order. - Compare
k
with the mid point of the list. - If it matches, return
True
- If the mid value is \(>\)
k
, then search the first half, else search the second half. - Stop when the interval to be searched becomes empty
- This apprach takes \(\log(n)\) time to search for an element at a worst case scenario.
Activity
Implement the binary search algorithm using recursion