### 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

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.

## Comments

## Post a Comment