I have to write a function which returns the index of the maximum value in a cyclic sorted array, without duplicates in O(logn).
I have already tried this code and it does work, but for some reason, I get an error when the array has 2 or 6 elements. I am not quite getting what is wrong with it that it works for every array length except for this two values.
int arr[];
int search;
int index=sizeof(arr)/sizeof(*arr) - 1;
int min=0;
int max=sizeof(arr)/sizeof(*arr) - 1;
int mid;
int m=index;
while (min!=max) {
mid=(min+max)/2;
if (arr[m] < arr[mid]) {
min=mid+1;
index=mid;
max=max;
}
else if (arr[m] > arr[mid]) {
max=mid-1;
min=min;
}
else {
index=m;
}
if (min==max)
break;
}
cout << index;
Examples:
Input: 1 2 3 4 5
Output: 4
Input: 3 4 5 1 2
Output: 2
Input: 9 1 2 3
Output: 0
Input: 1 2 or 1 2 3 4 5 6
Output: ERROR
I also included a cout<<min<<max<<mid
inside the while to inspect what happens when the length is 2 or 6, and what I get is an infinite loop of
"0-10" outputs.
I would appreciate any help. Thanks in advance!