# Find a peak element in a Given Array

Objective : In this article we will discuss an algorithm to Find a peak element in a Given Array. We will see the recursion techniques to solve this problem.

Peak Element: peak element is the element which is greater than or equal to both of its neighbors.

Input:  Array, arrA[] .

Output: A peak element and its index

Approach:

A simple approach is to do a linear scan to a array and using few variables we can find a peak element. But the Time Complexity will be O(n) but real question is, Can we do better?

The Answer is yes, by using Binary Search techniques.

• If middle element is the peak element, return it
• If middle element is smaller than its left element , we will get our peak element on the left half
• If middle element is the smaller than its right element, we will our peak element on the right.

Time Complexity : O(logN)

Notes:

1. If array has all the same elements, every element is a peak element.
2. Every array has a peak element.
3. Array might have has many peak elements but we are finding only one.
4. If array is in ascending or descending order then last element or the first element of the array will be the peak element respectively.

Complete Code:

 //we will use binary search techniques //if middle element is the peak element, return it //if middle element is smaller than its left element , we will get our peak element on the left half //if middle element is the smaller than its right element, we will our peak element on the right. public class PeakElement { public int peak(int [] arrA,int low, int high, int size){ int mid = (low+high)/2; if((mid==0||arrA[mid]>=arrA[mid–1]) && (arrA[mid]>=arrA[mid+1]||mid==size–1)){ return mid; } else if(mid>0 && arrA[mid]

view raw
PeakElement.java
hosted with ❤ by GitHub

Output:

```Peak Element is found at index [6] = 5
```

### 2 thoughts on “Find a peak element in a Given Array”

This site uses Akismet to reduce spam. Learn how your comment data is processed.