Algorithm: Binary Search in Array

Binary search algorithm is enhancement in searching of element in array, It reduces worst case complexity of of linear search from O(n) to O(log2n). In this algorithm all the elements in the array must be sorted.

BinarySearch(ArrayValues[], n, searchValue, LB, UB)

Here ArrayValues is an array of size n, Which is already sorted. In which we have to search an element searchValue. LB is lower bound and UB is an upper bound of the array. Mid is an intermediate variable which will contains middle element of array.

Step 1: till LB<=UB repeat step 2 and 3 
Step 2: Mid = (LB + UB)/2
Step 3: i) if ArrayValues[Mid] = searchValue then return Mid.
           ii) if ArrayValues[Mid] > searchValue then 
                       a) UB = Mid-1
               else
                      a)  LB = Mid+1
Step 4: return -1


Click here for Explanation

No comments:

Post a Comment