TIME COMPLEXITY
O (log n)
IMPLEMENTATION OF BINARY SEARCH
function binarySearchRecursive(arr, target, low, high):
if low > high:
return -1 // Base case: target not found
mid = low + (high - low) / 2 // Calculate the middle index
if arr[mid] == target:
return mid // Target found, return index
else if arr[mid] < target:
return binarySearchRecursive(arr, target, mid + 1, high) // Search in the right half
else:
return binarySearchRecursive(arr, target, low, mid - 1) // Search in the left half
This is very simple and easy to follow but it takes up more amount of space since each function call is stored in the computer's memory
function binarySearchIterative(arr, target):
low = 0
high = length(arr) - 1
while low <= high:
mid = low + (high - low) / 2 // Calculate the middle index
if arr[mid] == target:
return mid // Target found, return index
else if arr[mid] < target:
low = mid + 1 // Target is in the right half
else:
high = mid - 1 // Target is in the left half
return -1 // Target not found
This method is more space efficient
APPLICATIONS OF BINARY SEARCH
Searching in Dictionaries
Finding an element in a pre-sorted Array
FIRESHIP: Binary Search Algorithm in 100 Seconds
ABDUL BARI: Binary Search Iterative Method