-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeakElement.cpp
More file actions
51 lines (51 loc) · 998 Bytes
/
peakElement.cpp
File metadata and controls
51 lines (51 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// WE CAN DO THIS QUESTION ON 0(N) BY SIMPLE LINEAR SEARCH
// BUT
// WE WILL DO IT BY BINARY SEACRCH IN 0(LOG n)
#include <bits/stdc++.h>
using namespace std;
void printArray(int arr[], int n)
{
int i = 0;
cout << endl
<< "Array thus Modified is : ";
while (i < n)
{
cout << arr[i++] << " ";
}
}
int findPeak(int arr[], int n)
{
int s = 0;
int e = n;
int mid = s + (e - s) / 2;
while (s < e)
{
if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1])
return arr[mid];
else if (arr[mid] < arr[mid + 1])
{
s = mid + 1;
}
else
{
e=mid;
}
}
return s;
}
int main()
{
int n, i = 0;
cout << "Enter the number of Elements : ";
cin >> n;
int arr[n];
cout << "Enter the Elements : ";
while (i < n)
{
cin >> arr[i++];
}
printArray(arr, n);
cout << endl;
int ans = findPeak(arr, n);
cout << ans;
}