middle1hightarget else returnbinsearchx low middle 1target Explanation for

# Middle1hightarget else returnbinsearchx low middle

This preview shows page 6 - 7 out of 7 pages.

middle+1,high,target) else return(bin_search(x, low, middle-1,target) } Explanation for Binary Search : NOTE: In this diagram first is used in place of low , last is used in place of high . Solved Problem#3: (For Binary Search) #include <stdio.h> #define MAX_ARY_SIZE 12 int binarySearch (int x[], int low,int high, int target); //function prototype int main () { int i ,locn, target; int ary[MAX_ARY_SIZE] = { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91 }; Page 6 of 7
printf("Data: "); for (i = 0; i < MAX_ARY_SIZE; i++) printf("%3d", ary[i]); printf("\n\nEnter a key for search : "); scanf("%d", &target); do { locn= binarySearch (ary,0, MAX_ARY_SIZE - 1, target); if(locn!=-1) printf("%3d found at location: %2d\n", target, locn); else printf("%3d NOT found in array\n", target); printf("Enter next key or -1 to quit: "); scanf("%d", &target); } while (target != -1); printf("\n\nEnd of search.\n"); return 0; } /* end of main */ int binarySearch( int x[], int low, int high, int target) { int middle; if (low > high) /*base case1:target not found*/ return -1; middle = (low + high)/2; if (x[middle] == target) return (middle); /*base case2:target found*/ else if (x[middle] < target) return binarySearch(x, middle+1,high,target); else return binarySearch(x, low, middle-1,target); } Page 7 of 7

#### You've reached the end of your free preview.

Want to read all 7 pages?

• Spring '10
• zaman
• #include, #define, Search algorithm