1

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!

  • Hi, I fixed your code formatting a bit to make it easier for people to read. Please do this yourself the next time (or, even better, keep your code nicely formatted to make it easier to read it for yourself) – Daniel Jour Apr 28 '19 at 21:31
  • Can you please also add some example input along with the expected output and the actual output / error you're encountering? – Daniel Jour Apr 28 '19 at 21:32
  • Sure, and thanks for the edit. So example input/outputs are: 1,2,3,4,5,6,7 - 6 (case where it is sorted) 3, 4, 5, 1, 2 - 2 (5 is the biggest) Now when the input is: 1,5, no output occurs, just the cursor pulsating. Same if it has 6 elements – infinitedreamer666 Apr 28 '19 at 22:08
  • 1
    @infinitedreamer666 -- All of that information you put in your last comment should be in your original post, and in your code itself (instead of int `arr[]={...}`). You should be posting a [mcve]. – PaulMcKenzie Apr 28 '19 at 22:59

0 Answers0