Skip to content

Commit c8cb51e

Browse files
committed
Solution to Find in Mountain Array
1 parent 73fd6cd commit c8cb51e

2 files changed

Lines changed: 70 additions & 3 deletions

File tree

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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+
}

‎src/BinaySearch/MountainArray.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,15 @@ else if (nums[middle] > nums[middle+1]){
5858
/*
5959
Solution by Kunal Kushwaha
6060
*/
61-
static int peakIndexInMountainArray(int[] arr) {
61+
static int peakIndexInMountainArray(int[] nums) {
6262
int startIndex = 0;
63-
int endIndex = arr.length -1;
63+
int endIndex = nums.length -1;
6464

6565
while (startIndex < endIndex){
6666

6767
int middle = startIndex + (endIndex - startIndex)/2;
6868

69-
if (arr[middle] > arr[middle+1]){
69+
if (nums[middle] > nums[middle+1]){
7070
//You are in the Descending Part of the Array
7171
//This may be the answer but look at Left of the Array
7272
//This is why end!= mid -1;

0 commit comments

Comments
 (0)