Saturday, May 22, 2010

binary search on a circularly shifted array

A sorted array is shifted circularly (i.e m elements from start are removed from start and added to the end). Now write an algorithm to search for an element.


public static int bS(int[] a, int left, int right, int key) {

while (left <= right) {
int mid = left + (right - left) / 2;
if (a[mid] == key)
return mid;
if (a[left] > a[mid]) {
// switching has happened in left partition
// if key is less than the mid, sure it is in left partition
if (key > a[mid] && key <>
// then RP
left = mid + 1;
else
// LP
right = mid - 1; // for 2 cases, one is : if key <>


} else if (a[right] <>
// partition
if (key <> a[right])
// then LP
right = mid - 1;
else
// RP
left = mid + 1; // 2 cases, one is : if key > a[mid]just


} else
// following 2 are cases where there is no switching at all
if (key <>
// LP
right = mid - 1;
else
// RP
left = mid + 1;
}

return -1;
}

No comments:

Post a Comment