-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbs_find_partition.cpp
96 lines (90 loc) · 1.99 KB
/
bs_find_partition.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
#include <sstream>
#include <set>
#include <map>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define rrep(i,a,n) for(int i=n-1;i>=a;i--)
#define pb push_back
#define rb pop_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define sz(x) ((int)(x).size())
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const ll mod = 1000000007;
//Find partition in increasing then decreasing sequence
int bsFindPartition(VI ar){
int i=0,j=sz(ar)-1;
while(i<j){
int mid= i+(j-i)/2;
if(i==(j-1)){
return ar[mid]<=ar[mid+1]?mid+1:mid;
}
if(ar[mid]>ar[mid+1]&&ar[mid]>=ar[mid-1]){
return mid;
}
else if(ar[mid]>=ar[mid-1]&&ar[mid+1]>=ar[mid]){
i=mid+1;
}
else{
j=mid;
}
}
return -1;
}
//find element in the rotated sorted sequence
int bsFindInRotated(VI ar,int k){
int i=0,j=sz(ar)-1;
while(i<=j){
int mid=i+(j-i)/2;
if(ar[mid]==k){
return mid;
}
if(ar[mid]<ar[i]&&ar[mid]<ar[j]){
if(k>=ar[i]||k<ar[mid]){
j=mid-1;
}
else{
i=mid+1;
}
}
else if(ar[mid]>ar[i]&&ar[mid]>ar[j]){
if(k>ar[mid]||k<=ar[j]){
i=mid+1;
}
else{
j=mid-1;
}
}
else{
if(k>ar[mid])
i=mid+1;
else{
j=mid-1;
}
}
}
return -1;
}
int main(){
VI v;
v.pb(6);
v.pb(7);
v.pb(3);
v.pb(4);
v.pb(5);
cout<<bsFindInRotated(v,8);
}