Skip to content

Commit 5f51a8e

Browse files
committed
day 9 peak element
1 parent 2fc338a commit 5f51a8e

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ Include contains single header implementation of data structures and some algori
178178
| Find the missing number in Arithmetic Progression | [missingNumber2.cpp](sort_search_problems/missingNumber2.cpp) |
179179
| Find the common elements in 3 sorted vectors | [commonIn3Arrays.cpp](sort_search_problems/commonIn3Arrays.cpp) |
180180
| Find all the pairs with a given sum in an unsorted array/vector | [find_pairs_with_sum.cpp](sort_search_problems/find_pairs_with_sum.cpp) |
181+
| Given an array, find peak element in it. A peak element is an element that is greater than its neighbors.| [peak_element.cpp](sort_search_problems/peak_element.cpp) |
181182

182183
### Graph Problems
183184
| Problem | Solution |

sort_search_problems/peak_element.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Given an array, find peak element in it. A peak element is an element that is greater than its neighbors.
3+
* For example,
4+
*
5+
* Input : [8, 9, 10, 2, 5, 6]
6+
* Output: The peak element is 10
7+
* Input : [8, 9, 10, 12, 15]
8+
* Output: The peak element is 15
9+
* Input : [10, 8, 6, 5, 3, 2]
10+
* Output: The peak element is 10
11+
*/
12+
13+
#include <iostream>
14+
15+
int findPeak(int arr[], int n, int low, int high)
16+
{
17+
// mid point
18+
//
19+
int mid = (low + high) / 2;
20+
21+
// check if mid element is peak
22+
//
23+
if ((mid == 0 || arr[mid-1] <= arr[mid]) &&
24+
(mid == n-1 || arr[mid+1] <= arr[mid]))
25+
{
26+
return mid;
27+
}
28+
29+
// if left neighbour of mid is greater than mid element
30+
// then peak would be in left array.
31+
if (mid - 1 >= 0 && arr[mid-1] > arr[mid])
32+
{
33+
return findPeak(arr, n, low, mid-1);
34+
}
35+
36+
// search the right side otherwise.
37+
//
38+
return findPeak(arr, n, mid+1, high);
39+
}
40+
41+
int main()
42+
{
43+
int arr[] = {10, 20, 30, 25, 15};
44+
int n = sizeof(arr) / sizeof(arr[0]);
45+
46+
int peakIndex = findPeak(arr, n, 0, n-1);
47+
std::cout << "The peak element of the array is:" << arr[peakIndex]
48+
<< std::endl;
49+
return 0;
50+
}

0 commit comments

Comments
 (0)