Binary Search
Binary Search
-------------
Binary Search is a searching algorithm for finding an element's position in a
sorted array.
In this approach, the element is always searched in the middle of a portion of an
array.
Binary search can be implemented only on a sorted list of items. If the elements
are not sorted already, we need to sort them first.
Algorithm:
----------
The algorithm starts by comparing the target value with the middle element of the
sorted array/list.
If the target value is equal to the middle element, the search is successful.
If the target value is less than the middle element, the search continues in the
left half of the array/list.
If the target value is greater than the middle element, the search continues in the
right half of the array/list.
This process is repeated until the target element is found or the remaining
interval is empty (element not present).
Binary Search Algorithm can be implemented in two ways which are discussed below.
Iterative Method
----------------
do until the pointers low and high meet each other.
mid = (low + high)/2
if (x == arr[mid])
return mid
else if (x > arr[mid]) // x is on the right side
low = mid + 1
else // x is on the left side
high = mid - 1
Recursive Method
----------------
binarySearch(arr, x, low, high)
if low > high
return False
else
mid = (low + high) / 2
if x == arr[mid]
return mid
else if x > arr[mid] // x is on the right side
return binarySearch(arr, x, mid + 1, high)
else // x is on the left side
return binarySearch(arr, x, low, mid - 1)
Time Complexities
-----------------
Best case complexity: O(1)
Average case complexity: O(log n)
Worst case complexity: O(log n)
Space Complexity
----------------
The space complexity of the binary search is O(1).