Search

Saturday, March 22, 2014
0 comments

Algorithm for binary search for data structure in'C'

8:30 AMSaturday, March 22, 2014

Algorithm for binary search:

BINSEARCH (arr, n, key)
[‘arr’ elements are stored in ascending order]
success <--FALSE; FIRST<--1; LAST<--n
MID <--INTEGER((FIRST+LAST)/2)
Repeat While (FIRST <= LAST)
  If(arr[MID] = key) Then:
     success <-- TRUE; Return success
   Else:
     If arr[MID] > key Then:
       LAST <-- MID - 1
    Else:
      FIRST <-- MID + 1
    [End of If]
  [End of If]
[End of While]
Return success
Exit.
               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.

Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top