Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyClass {
- public static void main(String args[]) {
- int[] arr = {1, 3, 5, 7, 8};
- int idx = findLocalPeak(arr, 0, arr.length - 1);
- System.out.println(String.format("Result: index = %d, value = %d", idx, arr[idx]));
- }
- public static int findLocalPeak(int[] arr, int left, int right) {
- int n = right - left + 1;
- if (n==1) { return left; }
- if (n == 2) {
- if (arr[left]>=arr[right]) {
- return left;
- } else {
- return right;
- }
- }
- int mid = (int)Math.floor(n/2) + left;
- if (arr[mid-1]<=arr[mid]&&arr[mid+1]<=arr[mid]) {
- return mid;
- } else {
- if (arr[mid-1]>arr[mid]) {
- return findLocalPeak(arr, left, mid-1);
- } else {
- return findLocalPeak(arr, mid + 1, right);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement