package ArrayProb;

/**
 * Find Peak Element 
 * A peak element is an element that is greater than its neighbors.
 * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
 */

public class FindPeakElement {
	 
	public static void main (String[] args) {
		int[] A = { 1, 3 , 1};
		System.out.println(findPeakElement(A));
	}

	 public static int findPeakElement(int[] num) {
	     if (num.length == 0)  return -1;
	     if (num.length == 1) return num[0];
	     int l = 0;
	     int r = num.length - 1;
	     while (l <= r) {
	    	 int mid = l + (r - l) / 2;
	    	 if ((mid == l || num[mid - 1] <= num[mid])
	    			 && (mid == r || num[mid + 1] <= num[mid])) {
	    		 return mid;
	    	 }
	    	 else if (mid > l && num[mid - 1] > num[mid]) r = mid - 1;// pay attention!!!!!
	    	 else l = mid + 1;
	     }
	     return l;
	 }
	 
}
