-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotated.cpp
More file actions
130 lines (102 loc) · 2.6 KB
/
Copy pathrotated.cpp
File metadata and controls
130 lines (102 loc) · 2.6 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <iostream>
#include <vector>
#include <algorithm>
//#include <random>
#include<cstdlib>
#include <ctime>
#include <chrono>
#include <random>
#include<cassert>
using namespace std;
int bs(vector<int> &v, int t)
{
size_t N(v.size());
size_t l(0), r(N-1);
while (l <= r)
{
size_t m = l +((r-l)/2);
cout << "l " << l << " r " << r << " m " << m << endl;
assert(l >= 0);
assert(r < N);
assert( 0 <= m && m < N);
if (v[m] == t) return m;
if (v[m] < t )
l = m+1;
else
r = m-1;
}
return -1;
}
int pivot(vector<int> &v)
{
size_t N(v.size());
size_t l(0), r(N-1);
if (v[l] < v[r] || N == 1) // no rotation
return -1;
while (l <= r)
{
size_t m = l +((r-l)/2);
cout << "l " << l << " r " << r << " m " << m << endl;
assert(l >= 0);
assert(r < N);
assert( 0 <= m && m < N);
if (v[m] > v[m+1]) return m;
if (v[m] > v[0] )
l = m+1;
else
r = m-1;
}
return -1;
}
int main(int argc, char*argv[])
{
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 generator (seed); // mt19937 is a standard mersenne_twister_engine
//std::cout << "Random value: " << generator() << std::endl;
vector<int> v;
int n = 50;
if (argc > 1)
n = atoi(argv[1]);
for (int i = 0; i < n;++i)
v.push_back(generator());
// srand(time(NULL));
for (const int i: v)
cout << i << ' ';
sort(v.begin(),v.end());
cout << "\nsorted";
int j = 0;
for (const int i: v)
cout << i << "[" << j++ << "]" << ' ';
cout << endl;
int t = v[generator()%n];
if (argc > 2)
{
cout << "enter the number to find: ";
cin >> t;
}
size_t i = bs(v,t);
if (i == -1)
cout << "not found\n";
else
{
cout << t << " is at " << i << endl;
cout << "check " << v[i] << endl;
cout << "log2 " << log2(n) << endl;
}
cout << t << " via std bs" << binary_search(v.begin(), v.end(), t);
int r = generator()%(n-1);
cout << "rotation by " << r << "\n";
std::rotate(v.begin(), v.begin() + r, v.end());
j = 0;
for (const int i: v)
cout << i << "[" << j++ << "]" << ' ';
cout << endl;
int p = pivot(v);
cout << "pivot at " << p << endl;
bool b;
if (t < v[0])
b = binary_search(v.begin()+p, v.end(), t);
else
b = binary_search(v.begin(), v.begin()+p, t);
cout << "search result " << b << endl;
}