#include #include // Linear search in an unsorted array. void print_array(int a[], int n) { int i; printf("\nIndex i: "); for(i=0; i< n; i++) printf("%2d, ", i); printf("\nElement a[i]: "); for(i=0; i< n; i++) printf("%2d, ", a[i]); printf("\n\n"); } #define N 12 int main() { int a[N]= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91}; int i; print_array(a, N); // Search for the target using Binary Search // We assume that the array is already sorted in increasing order int target = 22; //int target = 72; // Try this target next printf("\nSearching for target= %d ...\n", target); int idx=-1; // if the target is found its index is stored here // initial values for the three search varaibles int first=0; int last= N-1; int mid= (first + last)/2; while(last >= first) { if( a[mid] == target) { idx=mid; // Found it! break; // exit the while loop } else if(a[mid] > target) { // don't search in a[mid] ... a[last] last = mid-1; } else { // don't search in a[first] ... a[mid] first = mid +1; } // recalculate mid for the next iteration mid = (first + last)/2; // integer division! } // end of while loop if(idx == -1) printf("Target not found.\n\n"); else printf("Target found at index: %d \n\n", idx); system("pause"); }