Search code examples
javaarraysalgorithmtime-complexitydivide-and-conquer

Find index of starting point of a sorted cyclic integer array


There are two sorted continuous number array merged in to a single array. Both the arrays had distinct numbers.

ex : 
{1, 2, 3, 4, 5, 6, 7, 8, 9}   and
{10, 11, 12, 13, 14}

int[] resultArr = {10, 11, 12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9};
                                      ^

Algorithm to find the index of the starting point. If we treat it as cyclic array, it will be in sorted order while iterating from the starting point.

In the above example the starting index will be "4"

I've wrote below sample program to solve this, but not happy about the time complexity.

Can someone tell me the time-complexity of the below code and provide a better solution for this problem.

public class FindStartingPoint {

  public static Integer no = null;

  private static void findStartingPoint(int[] arr, int low, int mid, int high) {
    if (no != null)
      return;
    else if (high - low <= 1)
      return;
    else if (arr[mid] > arr[mid + 1]) {
      no = mid + 1;
      return;
    }
    findStartingPoint(arr, low, (low + mid) / 2, mid);
    findStartingPoint(arr, mid, (mid + high) / 2, high);
  }

  public static void main(String[] args) {
    int[] arr = {12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
    findStartingPoint(arr, 0, arr.length / 2, arr.length - 1);
    System.out.println(no);
  }
}

Thanks in Advance. :-)


Solution

  • Binary search fits here too. Logarithmic.

    public int findStart(int[] numbers) {
        int low = 0;
        int high = numbers.length; // Exclusive
        while (low < high) {
            int middle = (low + high) / 2;
            boolean fitsLow = numbers[low] <= numbers[middle];
            if (fitsLow) {
                low = middle + 1;
            } else {
                high = middle;
            }
        }
        return low;
    }