Skip to content

Instantly share code, notes, and snippets.

@aswinsekar
Created October 7, 2018 07:35
Show Gist options
  • Save aswinsekar/de86ef36b48b8014afbf6a4daa55a9d4 to your computer and use it in GitHub Desktop.
Save aswinsekar/de86ef36b48b8014afbf6a4daa55a9d4 to your computer and use it in GitHub Desktop.
Some interesting modules in cpp
// 1d peak finding problem in lecture 1
// peak referred to local maximum
// there will be multiple local maximum, we need to find atleast one
#include<bits/stdc++.h>
using namespace std;
int peak(int arr[],int start,int end,int n){
int mid = start + (end-start)/2;
//checking mid index elemenet as peak by comparing with neighbours if the neighbours exist
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 peak(arr,start,mid-1,n);
else return peak(arr,mid+1,end,n);
}
int main(){
int n;
cout<<"Enter the numer of elements\t";
while(1){
cin>>n;
if(cin.good()){
break;
}
if(cin.fail()){
cin.clear();
cin.ignore();
cout<<"Enter a valid input\t";
}
}
cout<<"Enter array elements"<<endl;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"The peak is ";
cout<<arr[peak(arr,0,n-1,n)]<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment