Lesson 2: Introduction to Binary Search Algorithms
What is a binary search algorithm?
A binary search algorithm, like a linear search algorithm, is a way of finding a particular element on an array. It involves cutting an array in half and then removing the half where the element in question is not present. This process is repeated until the element in the array is found. Look at the diagram in the example for a better idea of the search method.
Binary search algorithm example
Search for the element "9" in the following array:
Step 1 Mid element = (low + high)/2In this case, the low element is 1 and the high element is 10. (low + high)/2 \n (1+10)/2 = 5.5 mid element= 5 See if element 9 is equal to the middle element of the array. 9 ≠ 5
Step 2Choose the half of the array in which element "9" lies. In this case, the second half is chosen. Repeat the process until you find element "9". See if element "9" is = to the middle element of the array 9 ≠ 8
Step 3Choose the half of the array in which element "9" lies. In this case, the second half is chosen again. From this we can see that element "9" lies on position no.8.
Real Life Example
The binary search algorithmic method can be used when trying to find your page number in a book. For example, many people open a book from the middle page and then if the page number they are on is higher they look to the pages on the right and if the number that they are on is lower, they look to the pages on the left.This process is repeated until the correct page number is found.
Advantages of binary search algorithms
Binary search algorithm is an efficient search algorithm as when you process through each step, half of the elements are eliminated, making it potentially quicker than the linear search algorithm method.
It is also more effective than the linear search method when it comes to large groups of data.
Key Terms
- Binary