Binary Search:- It is a method used to search an element present in an array. It can be implemented only on the sorted array. If you want to search an element using binary search you need to sort the array either in increasing order or decreasing order. Once the array is sorted you can implement binary search algorithm to find the position of the desired element. It's very fast as compared to linear search. You can use any sorting algorithm before implementing binary search algorithm.
It may also called half-interval search or logarithmic search.
Algorithm:-
Given an array 'array' of 'n' elements with values or records arry0 ... arrayn−1, sorted such that array0 ≤ ... ≤ arrayn−1, and target value 'search', the following subroutine uses binary search to find the index of 'search' in 'array'.
- Set 'first' to 0 and 'last' to n − 1.
- If first> last, the search terminates as unsuccessful.
- Set 'mid' (the position of the middle element) to the floor of (first + last) / 2.
- If arraym < search, set first to mid + 1 and go to step 2.
- If arraym > search, set last to mid – 1 and go to step 2.
- Now arraym = search, the search is done; return mid.
Here, we tried to search '76' using binary search :-
Complexities of Binary Search :-
No comments:
Post a Comment