|
| 1 | +package BinaySearch; |
| 2 | + |
| 3 | +public class FindInMountainArray { |
| 4 | + public static void main(String[] args) { |
| 5 | + |
| 6 | + } |
| 7 | + |
| 8 | + static void findInMountainArray(int[] array, int target){ |
| 9 | + |
| 10 | + |
| 11 | + } |
| 12 | + |
| 13 | + static int peakIndexInMountainArray(int[] nums) { |
| 14 | + int startIndex = 0; |
| 15 | + int endIndex = nums.length -1; |
| 16 | + |
| 17 | + while (startIndex < endIndex){ |
| 18 | + |
| 19 | + int middle = startIndex + (endIndex - startIndex)/2; |
| 20 | + |
| 21 | + if (nums[middle] > nums[middle+1]){ |
| 22 | + //You are in the Descending Part of the Array |
| 23 | + //This may be the answer but look at Left of the Array |
| 24 | + //This is why end!= mid -1; |
| 25 | + endIndex = middle; |
| 26 | + }else { |
| 27 | + //You are in the Ascending part of the Array |
| 28 | + startIndex = middle +1; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return startIndex; |
| 33 | + } |
| 34 | + |
| 35 | + static int orderAgnosticBinarySearch(int[] array, int target, int startIndex, int endIndex){ |
| 36 | + |
| 37 | + //Find whether the Array is sorted in Ascending or Descending |
| 38 | + boolean isAscending = array[startIndex] < array[endIndex]; |
| 39 | + |
| 40 | + while(startIndex <= endIndex){ |
| 41 | + //Find Middle Element |
| 42 | + int middle = (startIndex+endIndex)/2; |
| 43 | + if (target == array[middle]){ |
| 44 | + return middle; |
| 45 | + } |
| 46 | + |
| 47 | + if (isAscending){ |
| 48 | + if (target > array[middle]){ |
| 49 | + startIndex = middle+1; |
| 50 | + System.out.println("Start Index Incremented"); |
| 51 | + }else{ |
| 52 | + endIndex = middle-1; |
| 53 | + System.out.println("End Index Decremented"); |
| 54 | + } |
| 55 | + }else { |
| 56 | + if (target < array[middle]){ |
| 57 | + startIndex = middle+1; |
| 58 | + System.out.println("Start Index Incremented"); |
| 59 | + }else{ |
| 60 | + endIndex = middle-1; |
| 61 | + System.out.println("End Index Decremented"); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + return -1; |
| 66 | + } |
| 67 | +} |
0 commit comments