To overcome the disadvantage of linear search, we generally use binary search when the elements are sorted. Now, let us see ” What is binary search? What is the concept used in binary search?”
Definition : Binary search is a simple searching technique which can be applied if the items to be compared are either in ascending order or descending order.
The general idea used in binary search is similar to the way we search for the meaning of a word in dictionary. Obviously , we do do not use linear search. Instead , we open the dictionary in the middle and the word is compared with the element at the middle of the dictionary. If the word is found, the corresponding meaning is retrieved and the searching is finished. Otherwise , we search either the left part of the dictionary or the right part of the dictionary. If the word to be searched is less than the middle element, search towards left otherwise , search towards right. The procedure is repeated till key(word) is found or the key item (word) is not found.
Once we know the concept of binary search, the next question is “How to search for key in a list of elements?”
Now, let use see how to search for an item. The procedure is shown below:
Procedure: The program can be designed as follows. Here, low is considered as the position of the first element and high as the position of the last element. The position of the middle element can be obtained using the statement: mid=(low+high)/2;
the key to be achieved using the statement:
After executing the statement , if(key==a[mid]), if it is true, the message “successful search” is displayed. If this condition is false, key may be in the left part of the array or in the right part of the array . If the key is less than the middle element, the array in the left part has to be compared from low to mid-1. Otherwise, the right part of the array has to be compared from mid-1 to high.
This can be achieved by using the following statement:
Note that, as all the above statement are executed repeatedly, the gap between low and high will be reduced. Finally, the value of low may exceed the value of high, in that case we say that key is not found.
Now, the C program takes the following form:
You are already familiar with the algorithm and flowchart of binary search. Now the complete C program is shown below:
Note: The necessary condition for binary search is that the list of elements should be sorted. Otherwise, binary search should not be used. If elements are not sorted and are very less, normally we go for linear search. But, if the elements are more and not sorted, it is better to sort them and use binary search.
Advantages of binary search
- Simple Technique
- Very efficient searching technique.
- The list of elements where searching takes place should be sorted.
- It is necessary to obtained the middle element which is possible only if the elements are sorted in the array. If the elements are sorted in linked list , this method can not be used.