dcell59
November 28th, 2006, 04:08 PM
In a recent interview, I was asked to consider what was called a "rotated array". This data structure is an array where the data is sorted, but the beginning of the data is not neccessarily the first element of the array. For example, these arrays are equivalent:
{ 1, 2, 3, 4, 5 }
{ 3, 4, 5, 1, 2 }
{ 5, 1, 2, 3, 4 }
The interview questions involved figuring out how to search for an item in this array, given only the array and the size of the array - I was not given the index or value of the lowest data value. When I said I thought that it was bad design to pass around an incomplete data structure like this, I was told that this sometimes happened and that I might need to deal with a case like this.
I was able to come up with a linear search that would also note whether or not the beginning of the sorted list had been encountered, and use that information to reduce the search time.
We then discussed various search algorithms and talked about binary searches. The interviewer insisted that this could be done with a binary search - still without knowing where the lowest value is. Can anyone think of how this might be done?
It does seem like there is a property of such an array that can be applied: When you partition a rotated array, one partition will be sorted and the other will be a rotated array. Once you have split the array into two pieces, you can determine whether each piece is sorted. If the item being searched for is in the sorted piece, you can do a binary search. If not, you can recurse on the other piece. Does this seem like a valid method?
{ 1, 2, 3, 4, 5 }
{ 3, 4, 5, 1, 2 }
{ 5, 1, 2, 3, 4 }
The interview questions involved figuring out how to search for an item in this array, given only the array and the size of the array - I was not given the index or value of the lowest data value. When I said I thought that it was bad design to pass around an incomplete data structure like this, I was told that this sometimes happened and that I might need to deal with a case like this.
I was able to come up with a linear search that would also note whether or not the beginning of the sorted list had been encountered, and use that information to reduce the search time.
We then discussed various search algorithms and talked about binary searches. The interviewer insisted that this could be done with a binary search - still without knowing where the lowest value is. Can anyone think of how this might be done?
It does seem like there is a property of such an array that can be applied: When you partition a rotated array, one partition will be sorted and the other will be a rotated array. Once you have split the array into two pieces, you can determine whether each piece is sorted. If the item being searched for is in the sorted piece, you can do a binary search. If not, you can recurse on the other piece. Does this seem like a valid method?