|
|
A program to implement the binary search algorithm. |
|
#include <stdio.h> void binary_search(const int *, const int, const int); int main(void) { int arr[1000], i, v, cnt; /* Store the values in the array */ for( i = 0; i < 1000; i++ ) arr[i] = 10 + i * 2; printf( "\nEnter value to search : " ); scanf( "%d", &v ); binary_search(arr, v, 1000); return 0; } void binary_search(const int *p, const int val, const int sz) { int fi, li, mi, n, found = 0; /* Search the value in the array fi=first ,mi=milldle,li=last value */ n = 0; fi = 0; /* Lowest subscript - will always be 0 */ li = sz - 1; /* Highest subscript - will be dimension - 1 */ if(val < p[fi] || val > p[li]) { printf( "\n%d not found in the array", val); printf( "\nNo of attempts = 1" ); } else { printf( "\nAttempts\tFirst index\tLast index\tMiddle index\tarr[mi]" ); while(1) { n++; /* Calculate middle index */ mi = (fi + li) / 2; if( mi == fi || mi == li ) break; /* Processing complete */ printf( "\n\t%d\t%d\t\t%d\t\t%d\t\t%d", n, fi, li, mi, p[mi] ); if(val == p[mi] ) { found = 1; break; } if(val < p[mi]) { li = mi; continue; } if(val > p[mi]) { fi = mi; continue; } } /*End of while loop */ if(found) { printf( "\n%d found in the array", val); printf( "\nNo of attempts = %d", n ); } else { printf( "\n%d NOT found in the array", val); printf( "\nNo of attempts = %d", n ); } } /*End of else */ }
|
|
|
|
|
|
|
|