BINARY SEARCH:
This method is called binary search, as we have divided the list to be searched every time
into two lists and the search is done in only one of the lists. Consider that the list is sorted in
ascending order. In binary search algorithm, to search for a particular element, it is first
compared with the element at the middle position, and if it is found, the search is successful,
else if the middle position value is greater than the target, the search will continue in the first
half of the list; otherwise, the target will be searched in the second half of the list. The same
process is repeated for one of the halves of the list till the list is reduced to size one.
Algorithm depicts the logic behind this type of search.
algorithm
1. Let n be size of the list
Let target be the element to be searched
Let flag = 0, low = 0, high = n-1
2. if low £ high, then
middle = (low + high)/2
else go to step (5)
3. if(key[middle] = target)
Position = middle, fl ag = 1
Go to step (5)
else if(key[middle] > target) then
high = middle − 1
else
low = middle + 1
4. Go to step(2)
5. if flag = 1
report as target element found at location ‘position’
else
report that element is not found in the list
6. stop
CODE (C LANGUAGE)
/* BINARY SEARCH