-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeakFinder1D.cpp
More file actions
45 lines (40 loc) · 1.17 KB
/
Copy pathPeakFinder1D.cpp
File metadata and controls
45 lines (40 loc) · 1.17 KB
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
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int findPeakUtil(int *mas, int low, int high, int n)
{
// Find index of middle element
int mid = low + (high - low) / 2;
// Compare middle element with its neighbours (if neighbours exist)
if ((mid == 0 || mas[mid - 1] <= mas[mid]) &&
(mid == n - 1 || mas[mid + 1] <= mas[mid]))
return mas[mid];
// If middle element is not peak and its left neighbour is greater
// than it, then left half must have a peak element
else if (mid > 0 && mas[mid - 1] > mas[mid])
return findPeakUtil(mas, low,(mid - 1), n);
// If middle element is not peak and its right neighbour is greater
// than it, then right half must have a peak element
else return findPeakUtil(mas, (mid + 1), high, n);
}
int findPeak(int *mas, int n)
{
return findPeakUtil(mas, 0, n-1, n);
}
int main()
{
unsigned int Size = 0;
cout << "Size of array: ";
cin >> Size;
cin.sync();
int *Array = new int[Size];
cout << "-------ENTER OF ARRAY---"<<endl;
for (int i = 0; i < Size; ++i)
{
//cout << "Enter " << i << " element of array: ";
cin >> Array[i];
cin.sync();
}
cout << "Peak is: " << findPeak(Array,Size);
}