Algorithm for binary search for data structure in'C'

Algorithm for binary search:

BINSEARCH (arr, n, key)
[‘arr’ elements are stored in ascending order]
success <--FALSE; FIRST<--1; LAST<--n
Repeat While (FIRST <= LAST)
  If(arr[MID] = key) Then:
     success <-- TRUE; Return success
     If arr[MID] > key Then:
       LAST <-- MID - 1
      FIRST <-- MID + 1
    [End of If]
  [End of If]
[End of While]
Return success
               In this algorithm when the while loop terminates the variable ‘success’ assigned with FALSE is returned. When the search is successful the algorithm terminates by returning the value of variable ‘success’ as TRUE. So we can check easily from the algorithm that the search unsuccessful when the variable value FIRST is greater then that of LAST.


Post a Comment