-
Notifications
You must be signed in to change notification settings - Fork 17
/
pivot (1).cpp
53 lines (40 loc) · 942 Bytes
/
pivot (1).cpp
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
52
53
#include <iostream>
using namespace std;
//Find Pivot in sorted rotated array
void approach1(int n, int a[]){
for(int i=0;i<n;++i){
if(a[i]> a[i-1] && a[i]>a[i+1]){
cout << "Approach 1- "<< i <<endl;
}
}
}
void approach2(int n, int a[], int s, int e){
int mid;
while(s<=e){
mid=(s+e)/2;
//mid is Pivot if is greater than right next
if(a[mid]>a[mid+1] && mid<e)
cout << "Approach 2- "<< mid;
//mid-1 will be Pivot if mid< mid-1
if(a[mid]<a[mid-1] && mid>s)
cout<<"Approach 2- "<< mid-1;
//if left half unsorted, it means Pivot is in left half
if(a[s]>a[mid]){
e=mid-1;
}else{
s=mid+1;
}
}
}
int main() {
int n;
cin>>n;
int a[n];
for(int i=0;i<n;++i){
cin>>a[i];
}
approach1(n,a);
int s=0;
int e=n-1;
approach2(n,a,s,e);
}