#include<stdio.h> // Simple binary search algorithm int binarySearch(int arr[], int l, int r, int x) { if (r>=l) { int mid = l + (r - l)/2; printf("%s %d l %d r-1 %d mid %d arr[mid] %d\n",__func__, __LINE__, l, r-1, mid, arr[mid]); if (arr[mid] == x) { printf("%s %d mid %d\n",__func__, __LINE__, mid); return mid; } if (arr[mid] > x) { printf("%s %d l %d mid %d\n",__func__, __LINE__, l, mid); return binarySearch(arr, l, mid-1, x); } printf("%s %d mid+1 %d r %d\n",__func__, __LINE__,mid+1, r); return binarySearch(arr, mid+1, r, x); } return -1; } int findPos(int arr[], int key) { int l = 0, h = 1; int val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high h = 2*h; // double high index val = arr[h]; // update new val printf("%s %d low %d high %d val %d\n",__func__, __LINE__, l, h, val); } // at this point we have updated low and // high indices, Thus use binary search // between them printf("%s %d \n",__func__, __LINE__); return binarySearch(arr, l, h, key); } // Driver program int main() { int arr[] = {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170}; int ans = findPos(arr, 10); if (ans==-1) { printf("Element not found"); } else { printf("Element found at index %d", ans); } return 0; }
Output:
findPos 36 low 1 high 2 val 7
findPos 36 low 2 high 4 val 10
findPos 42
binarySearch 10 l 2 r-1 3 mid 3 arr[mid] 9
binarySearch 19 mid+1 4 r 4
binarySearch 10 l 4 r-1 3 mid 4 arr[mid] 10
binarySearch 12 mid 4
Element found at index 4
|
Comments
Post a Comment