// pseudocode int findMaxIndex(int[] arr, int lo, int li) { int mid = (lo + hi)/2; if(arr[lo] < arr[mid]) return findMaxIndex(arr, mid, hi); else return findMaxIndex(arr, lo, mid); }There is one special case that we need to be considered if the array does not rotated at all, then above code will fail. for example, given [1, 2, 3, 4] However, we can just compare the most left and most right elements in the array
if([lo] < [hi]) the array does not rotate at all, the index of maximum value is [hi]
/** 1. arr = {1}, 2. 2 1 mid = arr[0] 3. 1 2 mid = arr[0] 2 3 4 1 (lo=0, hi=3) mid = 1 (lo=1, hi =3) -> 3 4 1 mid = 2 (lo=2, hi=3) -> 4 1 mid = 2 arr[2] < arr[2] max(arr, lo=2, hi=2) => 4 rotate sorted string */ public static int max(int[] arr, int lo, int hi){ if(arr[lo] <= arr[hi]){ return arr[hi]; }else{ int mid = (lo + hi)/2; if(arr[lo] < arr[mid]){ return max(arr, mid, hi); }else{ return max(arr, lo, mid); } } }
// Find the index of minimum element of an array // Make sure to test the case [2, 1] public static int findMinimumIndex(int[] arr, int lo, int hi){ if( arr[lo] <= arr[hi]) return arr[lo]; else{ // [2, 1] // [3, 1, 2] // =>[3, 1] => [1] int mid = (lo + hi)/2; if(arr[lo] < arr[mid]) return findMinimumIndex(arr, mid, hi); else if(arr[lo] > arr[mid]) return findMinimumIndex(arr, lo, mid); } } public static int findMaximumIndex(int[] arr, int lo, int hi){ if(arr[lo] <= arr[hi]) return arr[hi]; else{ // [2, 1] int mid = (lo + hi)/2; if( arr[lo] < arr[mid]) return findMaximumIndex(arr, mid, hi); else if(arr[lo] > arr[mid]) return findMaximumIndex(arr, lo, mid); } }
// make sure check the case [2 1] int findIndexMinimum array lo hi // no rotation if(array[lo] <= array[hi]) return lo else mid = lo + hi/2 if array[lo] < array[mid] findIndexMinimum array mid+1 hi // 2 1, 3 1 2 else findIndexMinimum array lo mid