Created
November 29, 2020 10:43
-
-
Save abhishek2x/da31a123fec8af34893ad1efbab1b3f3 to your computer and use it in GitHub Desktop.
Finding the peak of an array
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
/*! | |
* Finding the peak of an array | |
*/ | |
#include <bits/stdc++.h> | |
using namespace std; | |
#define ll long long int | |
int main(){ | |
ios :: sync_with_stdio(false); | |
cin.tie(0); | |
vector<int> a = {1, 4, 5, 10, 7, 3, 5, 2}; | |
int l=0, h=a.size()-1, mid; | |
while(l <= h){ | |
mid = l + (h-l)/2; | |
if(mid == 0){ | |
if(a[mid] > a[mid+1]){ | |
cout << a[mid]; | |
// break; | |
} | |
} else if (mid == a.size()-1){ | |
if(a[mid] > a[mid-1]){ | |
cout << a[mid]; | |
// break; | |
} | |
} else if(a[mid]>a[mid-1] && a[mid] > a[mid+1]){ | |
cout << a[mid] << "\n"; | |
// break; | |
} | |
else if(a[mid] < a[mid-1]){ | |
l = mid+1; | |
} else { | |
h = mid-1; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment