BINARY SEARCH
WHAT IS BINARY SEARCH ???

Binary Search is an efficient algorithm for finding an item from a list of items by repeatedly dividing the search interval in half.
THERE IS ONE CONDITION

THE LIST OR ARRAY MUST BE SORTED
How does it work ?
3 important Components

1. START POINTER
2. MID POINT
3. END POINTER
Set pointers at the start and end of the range
Locate Mid point index
Compare target with the middle index
Adjust pointers accordingly and repeat
TIME COMPLEXITY
O (log n)
IMPLEMENTATION OF BINARY SEARCH
RECURSIVE IMPLEMENTATION
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
RECURSIVE IMPLEMENTATION
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
O(log n)
ITERATIVE IMPLEMENTATION
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
ITERATIVE IMPLEMENTATION
This method is more space efficient
O( 1 )
APPLICATIONS OF BINARY SEARCH
Searching in Dictionaries

Finding an element in a pre-sorted Array

Further Reading and Relevant Links
FIRESHIP: Binary Search Algorithm in 100 Seconds
ABDUL BARI: Binary Search Iterative Method
Leetcode challenges on Binary search? Already there !

Thank you !!!!

BINARY SEARCH
By Chineletam Ugwuadu (Letam)
BINARY SEARCH
- 179