I have a sorted list which is rotated and would like to do a binary search on that list to find the minimum element.
Lets suppose initial list is {1,2,3,4,5,6,7,8}
rotated list can be like {5,6,7,8,1,2,3,4}
Normal binary search doesn’t work in this case. Any idea how to do this.
— Edit
I have one another condition. What if the list is not sorted??
A slight modification on the binary search algorithm is all you need; here’s the solution in complete runnable Java (see Serg’s answer for Delphi implementation, and tkr’s answer for visual explanation of the algorithm).
This prints:
See also
Integer[]instead ofint[]>>> 1instead of/ 2On duplicates
Note that duplicates makes it impossible to do this in
O(log N). Consider the following bit array consisting of many1, and one0:This array can be rotated in
Nways, and locating the0inO(log N)is impossible, since there’s no way to tell if it’s in the left or right side of the “middle”.Then, unless you want to sort it first and proceed from there, you’ll have to do a linear search to find the minimum.
See also