Given a sorted but rotated array how do you find the pivot ? I was asked this question in an interview. What is a rotated array ?
I got this on internet but its not clear at all.
In a rotated sorted array, only one of A and B can be guaranteed to be sorted.
Pivot is the element which is lesser then in left element and right element as well.
I think a sorted, rotated array is something like this:
Sorted:
Rotated:
2is the pivot. You need to find the position of the pivot.Solution should be simple:
the pivot is the point where the sorting ends and starts again. This is also what you “found on the Internet”:
(assuming array is sorted in ascending order. If descending order, change
<to>)Added: A divide and conquer logic that I could quickly think of. Keep spliting the array as long as the first element is larger than the last element. If the first element of the split (sub) array is not larger than the last element, the first is the pivot of the original array.
BTW, if you were asked this question in an interview, and you did not know what a sorted rotated array is, you can ask. If the interviewer explain it to you and then you give them a solution, you should be good. Personally I wouldn’t care if someone does not know terminology. As long as they can think, find logic and code, it should be fine.