Solution #1: This problem can be solved in O(log n) by modifying binary search as follows,
int search(int* arr, int strt, int end) { int mid = (strt+end)/2; if((arr[mid-1] < arr[mid]) && (arr[mid] > arr[mid+1])) return arr[mid]; else if(arr[mid-1] < arr[mid]) return search(arr, mid+1, end); else if(arr[mid] > arr[mid+1]) return search(arr, strt, mid-1); } int main() { int arr[10] = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4}; printf("%d\n", search(arr, 0, 9)); return 0; }
No comments:
Post a Comment