I have tried the following code to find out the minimum element in a cyclic sorted array. But it fails when the low = 1 and high =2 because the mid is always 1 and a[mid]=a[1] is always greater than the a[high].
I am trying to use Binary Search here to find the solution.
//finding the minim element in the 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 is %d",arrC[mid+1]);
There are 2 problems with your code
mid = low + (high-low)/2;
Don't use (low+high)/2
. This can cause the sum to exceed the limit of integer and will result in a negative value. One more reason your code can fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With