Stefan Deutschmann
Stefan Deutschmann

Reputation: 238

Need an algorithm for a special array (linear field)

I have an Array (linear field) with pre sorted numbers

 [1, 2, 3, 4, 5, 6],

but these arra y is shift to the right (k times),

now its

[5,6,1,2,3,4], k = 2

But I don´t know k. Only the array A.

Now I need an Algorithm to find the max in A (with runtime O(logn))

I think its something with binary search, can anyone help me??

Upvotes: 2

Views: 172

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

The question can be re-stated in terms of finding the "point of discontinuity", i.e the index of the 6, 1 spot in the array. You can do it iteratively using an approach similar to that of a binary search, like this:

Take an array A and two indexes, low and high, initially set to 0 and A.Length-1. The spot of discontinuity is between low and high.

Divide (low, high) in half. Call the midpoint mid. Compare A[low] to A[mid] and A[mid] to A[high]. If only one pair is ordered correctly, adjust the endpoint: if it's the low-mid pair that's ordered, assign low = mid, otherwise assign high = mid. If both intervals are ordered, the answer is A[high].

This runs in O(LogN) because each step reduces the size of the problem in half.

Upvotes: 2

Jamie
Jamie

Reputation: 1937

If you know what 'k' is, then you could either split the array and rebuild it, or you could reimplement a binary search algorithm that offsets by k.

For example,

int low = 0;
int high = array.length - 1;

while(low != high)
{
    int test = (low + high)/2;
    int testIndex = (test + k) % array.length;
    if (array[testIndex] < wanted)
        low = test;
    else if (array[testIndex] > wanted)
       high = test;
    else
       return testIndex;
 }

Or something like that. The testIndex variable is offset by 'k', but the search indexes (low, high, and test) don't know that.

PS., You will need to add more safety checks to this code (eg., 'wanted' not in array); I just wanted to show the index offset part.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490308

You're correct that it's basically a binary search.

Pick the middle number. If that's smaller than the number at the left end (of the current partition) then the largest number is in the left partition. Otherwise, it's in the right partition.

Upvotes: 1

Related Questions