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??
The question can be re-stated in terms of finding the “point of discontinuity”, i.e the index of the
6, 1spot in the array. You can do it iteratively using an approach similar to that of a binary search, like this:Take an array
Aand two indexes,lowandhigh, initially set to0andA.Length-1. The spot of discontinuity is betweenlowandhigh.Divide
(low, high)in half. Call the midpointmid. CompareA[low]toA[mid]andA[mid]toA[high]. If only one pair is ordered correctly, adjust the endpoint: if it’s thelow-midpair that’s ordered, assignlow = mid, otherwise assignhigh = mid. If both intervals are ordered, the answer isA[high].This runs in
O(LogN)because each step reduces the size of the problem in half.