-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
51482db
commit 14c8835
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
#include<bits/stdc++.h> | ||
#include <iostream> | ||
|
||
using namespace std; | ||
|
||
// A peak element in an array is the one that is not smaller than its neighbours. | ||
// Given an array arr[] of size N, find the index of any one of its peak elements. | ||
|
||
int findPeakUtil(int arr[], int low, int high, int n) | ||
{ | ||
int mid = low + (high - low) / 2; | ||
|
||
if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) | ||
return mid; | ||
|
||
else if (mid > 0 && arr[mid - 1] > arr[mid]) | ||
return findPeakUtil(arr, low, (mid - 1), n); | ||
|
||
else | ||
return findPeakUtil(arr, (mid + 1), high, n); | ||
} | ||
|
||
|
||
int peakElement(int arr[], int n) | ||
{ | ||
return findPeakUtil(arr, 0, n - 1, n); | ||
|
||
} | ||
|
||
|
||
int main() | ||
{ | ||
int n; | ||
cin>>n; | ||
int arr[n]; | ||
for(int i=0;i<n;i++) | ||
cin>>arr[i]; | ||
|
||
cout<<peakElement(arr,n); | ||
|
||
return 0; | ||
} |