c - finding the minimum element in a cyclic sorted array -
this question has answer here:
i have tried following code find out minimum element in cyclic sorted array. fails when low = 1 , high =2 because mid 1 , a[mid]=a[1] greater a[high].
i trying use binary search here find solution.
//finding minim element in cyclic sorted array int arrc[]={10,13,1,3,4,5,8}; int low=0,high =6; int mid=0,reset =1; while (low < high) { mid = (low+ high)/2; if (arrc[mid]>arrc[high]) { low = mid; } else if (arrc[mid] < arrc[high]) { high = mid; } } printf("minimum element %d",arrc[mid+1]);
use normal binary search, if arrc[high] < arrc[low]
, treat arrc[high]
infinity account wrap around. change line:
if (arrc[mid]>arrc[high])
to:
if (arrc[high] < arrc[low] || arrc[mid] > arrc[high])
Comments
Post a Comment