Skip to content

Commit 0b063ae

Browse files
committed
My Solution to find the peak element in a Mountain Array
1 parent 14c0b0f commit 0b063ae

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

‎src/BinaySearch/MountainArray.java‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,57 @@
22

33
public class MountainArray {
44
public static void main(String[] args) {
5+
//[1,2,3,1]
6+
//[1,2,1,3,5,6,4]
7+
int[] array = {1,2,3,6,5,4,3,2,1};
8+
// int[] array = {1,2,1,3,5,6,4};
9+
// int[] array = {1,2,3,1};//[2,1]
10+
// [6,5,4,3,2,3,2]
11+
// int[] array = {6,5,4,3,2,3,2};
12+
System.out.println("Peak Index Value is " + findPeakIndexFromArray(array));
13+
System.out.println("Peak Number is " + array[findPeakIndexFromArray(array)]);
14+
}
15+
16+
static int findPeakIndexFromArray(int[] nums){
17+
18+
int peakIndex = -1;
19+
20+
int startIndex = 0;
21+
int endIndex = nums.length -1;
522

23+
while (startIndex <= endIndex){
24+
//Find Middle Element
25+
int middle = startIndex + (endIndex - startIndex)/2;
26+
System.out.println("Middle Value is " + middle);
27+
28+
if (nums.length == 1){
29+
return nums[0];
30+
}else if (nums.length == 2){
31+
if (nums[0] < nums[1]){
32+
return 1;
33+
}else {
34+
return 0;
35+
}
36+
}
37+
38+
if (nums[middle] > nums[middle-1] && nums[middle] > nums[middle +1]){
39+
System.out.println("Returning Middle Index in if condition is " + middle);
40+
return middle;
41+
}
42+
else if (nums[middle] > nums[middle+1]){
43+
endIndex = middle;
44+
System.out.println("End Index Changed to " + middle);
45+
// System.out.println("Start Index Incremented");
46+
}else if(nums[middle] < nums[middle+1]){
47+
startIndex = middle;
48+
System.out.println("Start Index Changed to " + middle);
49+
// System.out.println("End Index Decremented");
50+
}else {//if (nums[middle] > nums[middle+1] && nums[middle] < nums[middle-1])
51+
System.out.println("Returning Middle Index in else condition is " + middle);
52+
return middle;
53+
}
54+
}
55+
return peakIndex;
656
}
57+
758
}

0 commit comments

Comments
 (0)