Data Structures & Algorithms Binary Search
Data Structures & Algorithms Binary Search
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm
works on the principle of divide and conquer. For this algorithm to work properly the data collection
should be in sorted form.
Binary search search a particular item by comparing the middle most item of the collection. If match
occurs then index of item is returned. If middle item is greater than item then item is searched in sub-
array to the right of the middle item other wise item is search in sub-array to the left of the middle item.
This process continues on sub-array as well until the size of subarray reduces to zero.
First, we shall determine the half of the array by using this formula −
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
The value stored at location 7 is not a match, rather it is less that what we are looking for. So the value
must be in lower part from this location.
We compare the value stored ad location 5 with our target value. We find that it is a match.
Pseudocode
The pseudocode of binary search algorithm should look like this −
Procedure binary_search
A ← sorted array
n ← size of array
x ← value ot be searched
Set lowerBound = 1
Set upperBound = n
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
To see binary search implementation using array in C programming language, please click here .
Advertisements
Write for us FAQ's Helping Contact
© Copyright 2016. All Rights Reserved.