#include <stdio.h> #include <stdlib.h> #define NR (x) (sizeof (x)/sizeof (x[0])) int Binaryserach ( int A[],int Size,int p) {int L = 0;//Find the left endpoint of the interval int R = size-1;//Find the right endpoint of the interval int mid, while (L <= R) //If the lookup interval is not empty Continue looking for {mid = L + (r-l)/2;//Take the subscript if (p = = A[mid]) to the middle element of the search interval return mid;//returns the subscript of the corresponding array element else if (P > Mid) L = mid + 1;
//sets the left endpoint of the new lookup interval else R = mid-1; Sets the right endpoint of the new find interval}return-1;} int main (void) {int a[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int ret = Binaryserach (A,nr (a), 8);//Returns the subscript of the found array element prin TF ("ret:%d a[%d]:%d\n", Ret,ret,a[ret]); return 0;}
Operation Result:
Realization of the binary algorithm C