Created
June 15, 2017 04:18
-
-
Save anil477/498507d278634588af72b8ef25ff4f0b to your computer and use it in GitHub Desktop.
Peak Element in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is very similar to the local minimai in an array - | |
// http://www.geeksforgeeks.org/find-a-peak-in-a-given-array/ | |
class PeakElement { | |
public static Integer getPeakElement(int[] array) { | |
if (array == null || array.length == 0) { | |
return null; | |
} | |
int n = array.length; | |
int start = 0; | |
int end = n - 1; | |
while (start <= end) { | |
int mid = (start + end) / 2; | |
if ((mid == 0 || array[mid - 1] <= array[mid]) && (mid == n - 1 || array[mid] >= array[mid + 1])) { | |
return array[mid]; // array[mid] is peak element | |
} else if (mid > 0 && array[mid - 1] > array[mid]) { | |
end = mid - 1; | |
} else { | |
start = mid + 1; | |
} | |
} | |
return null; | |
} | |
public static void main(String[] args) { | |
int[] array = { 15, 20, 25, 35, 45, 50, 60 }; | |
Integer peak = getPeakElement(array); | |
System.out.println(peak != null ? "Peak Element is " + peak : "No peak element!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment