Saturday, September 3, 2011

Searching a pivot in the sorted rotated array

Implement the following function, FindSortedArrayRotation, which takes as its input an array of unique integers that has been sorted in ascending order, then rotated by an unknown amount X where 0 <= X <= (arrayLength – 1). An array rotation by amount X moves every element array[i] to array[(i + X) % arrayLength]. FindSortedArrayRotation discovers and returns X by examining the array.

Solution:
This time you have to search for the rotation pivot. There is a subtle observation. This problem is in fact the same as finding the minimum element’s index. If the middle element is greater than the right most element, then the pivot must be to the right; if it is not, the pivot must be to the left.

1
2
3
4
5
6
7
8
9
10
11
12
13
int FindSortedArrayRotation(int A[], int N) {
  int L = 0;
  int R = N - 1;
 
  while (A[L] > A[R]) {
    int M = L + (R - L) / 2;
    if (A[M] > A[R])
      L = M + 1;
    else
      R = M;
  }
  return L;
}

Some Test Cases:

{ 1 }
return 0

{ 1, 2 }
return 0

{ 2, 1 }
return 1

{ 1, 2, 3 }
return 0

{ 3, 1, 2 }
return 1

{ 2, 3, 1 }
return 2

{ 1, 2, 3, 4, 5 }
return 0

{ 2, 3, 4, 5, 1 }
return 4

{ 3, 4, 5, 1, 2 }
return 3

{ 4, 5, 1, 2, 3 }
return 2

{ 5, 1, 2, 3, 4 }
return 1

{ 1, 2, 3, 4, 5, 6 }
return 0

{ 2, 3, 4, 5, 6, 1 }
return 5

{ 3, 4, 5, 6, 1, 2 }
return 4

{ 4, 5, 6, 1, 2, 3 }
return 3

{ 5, 6, 1, 2, 3, 4 }
return 2

{ 6, 1, 2, 3, 4, 5 }
return 1

{ 6, 8, 1, 2, 4, 5 }
return 2

3 comments:

  1. Does not work in all cases...
    { 3, 4, 5, 1, 2 }
    return 3

    Returning 3 when it should have been 2 :(.

    ReplyDelete
    Replies
    1. The answer should be 3 in your case. Why should it be 2?

      Delete