Skip to content

Commit 9824a08

Browse files
Merge pull request #274 from MohammedHassan07/peak
Solution of Peak element in the array added
2 parents e96e33e + 4e4ba56 commit 9824a08

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

LeetCode/FindPeak.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class FindPeak {
2+
3+
public static void main(String[] args) { // Question: Find peak value in zig-zag array
4+
// In this problem we are using binary search
5+
6+
int[] arr = {1, 2, 4, 5, 3, 2, 1, 2};
7+
// int[] arr = {2, 5, 7, 8, 10, 7, 6, 3, 2, 3, 4, 6, 10, 7, 3, 1,};
8+
System.out.println(peak(arr)); // Calling the function and printing the return value
9+
}
10+
11+
// Method to find index of the peak value
12+
public static int peak(int[] arr) {
13+
14+
int startIndex = 0;
15+
int LastIndex = arr.length - 1;
16+
17+
while (startIndex < LastIndex) {
18+
19+
int midElement = startIndex + (LastIndex - startIndex) / 2; // Finding middle element
20+
21+
if(arr[midElement] > arr[midElement + 1]) { //whole logic
22+
23+
LastIndex = midElement; // of the
24+
25+
} else if(arr[midElement] < arr[midElement + 1]){ // program
26+
27+
startIndex = midElement + 1; // is enclosed in this block
28+
}
29+
}
30+
return LastIndex; // At the end startIndex and LastIndex will point at same index so return LastIndex or startIndex.
31+
}
32+
}

0 commit comments

Comments
 (0)