Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the minimum element in a cyclic sorted array [duplicate]

Tags:

c

algorithm

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]); 
like image 629
krrishna Avatar asked Oct 21 '22 03:10

krrishna


1 Answers

There are 2 problems with your code

  • As pointed by Paulpro...treat arrC[high] as infinity..
  • Apart from that I would also suggest you to use

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.

like image 83
nikoo28 Avatar answered Oct 31 '22 11:10

nikoo28