Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. public class MyClass {
  2.     public static void main(String args[]) {
  3.         int[] arr = {1, 3, 5, 7, 8};
  4.        
  5.         int idx = findLocalPeak(arr, 0, arr.length - 1);
  6.         System.out.println(String.format("Result: index = %d, value = %d", idx, arr[idx]));
  7.     }
  8.    
  9.     public static int findLocalPeak(int[] arr, int left, int right) {
  10.         int n = right - left + 1;
  11.         if (n==1) { return left; }
  12.         if (n == 2) {
  13.             if (arr[left]>=arr[right]) {
  14.                 return left;
  15.             } else {
  16.                 return right;
  17.             }
  18.         }
  19.        
  20.         int mid = (int)Math.floor(n/2) + left;
  21.         if (arr[mid-1]<=arr[mid]&&arr[mid+1]<=arr[mid]) {
  22.             return mid;
  23.         } else {
  24.             if (arr[mid-1]>arr[mid]) {
  25.                 return findLocalPeak(arr, left, mid-1);
  26.             } else {
  27.                 return findLocalPeak(arr, mid + 1, right);
  28.             }
  29.         }
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement