Thursday, April 8, 2010

Search in a circular sorted array

Given an sorted array, say {1,2,3,4,5}, it's easy to use binary search.

If the array is circular, so we don't know where is the start, say {3,4,5,1,2} . Obviously linear search still works. But then how to do binary search? See here for an explanation. The following recursive idea is from this reference.

// find n in array.
function bsearch (array, n) {
If (array.size() == 1) {
if (n == array[0]) return FOUND.
else return NOT_FOUND.
} Else {
// Find middle point of the array.
// Now either left or right half of the array must be correctly sorted.
// Find which half it is *.
// (If both halves are sorted, then entire array is sorted)

// Check if n is in the correctly sorted half.
// If it is, run regular binary search on that half.
// Otherwise, recursively call this function on the improperly sorted half
}
}

* The idea is:

If the first element is less than the midpoint, the first half of the array is correctly sorted.
If the midpoint is less than the last element, the second half of the array is correctly sorted.
This follows from the fact that every element in the array is sorted with respect to the next element, except at the pivot.

No comments:

Blog Archive

Followers