Friday, January 29, 2016

Find sorted array rotation size

Find sorted array rotation size

Problem:
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:
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 (L < R) {
    int M = (L + R)/2;
    if (A[M] > A[R])
      L = M + 1;
    else
      R = M;
  }
  return L;
}
Click here for more Programming Interview Questions



No comments:

Post a Comment