-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.cpp
More file actions
87 lines (63 loc) · 1.57 KB
/
quicksort.cpp
File metadata and controls
87 lines (63 loc) · 1.57 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
#include <vector>
#include <unordered_set>
#include <cstdlib>
#include <iostream>
inline int partition (std::vector<int>& in, int& begin, int& end)
// partition the vector for the quicksort algorithm
// returns the index of the new pivot
{
int pivot = end - 1;
int left = begin;
int right = pivot-1;
while (true) { // loop will always eventually reach return statement
while (in[left] <= in[pivot] && left < pivot) {
++left;
}
while (in[right] >= in[pivot] && right > begin) {
--right;
}
if (left >= right) {
int tmp = in[left]; // swap left and pivot values
in[left] = in[pivot];
in[pivot] = tmp;
return left; // change pivot to left index
}
int tmp = in[left]; // swap left and right values
in[left] = in[right];
in[right] = tmp;
left = begin; right = pivot-1;
}
}
void quicksort(std::vector<int>& in, int begin=0, int end=-1)
// quicksort implementation
{
if (end == -1)
end = in.size();
if (end - begin <= 0)
return;
int pivot = partition(in, begin, end);
quicksort(in, begin, pivot);
quicksort(in, pivot+1, end);
}
int main(int argc, char** argv) {
std::srand(109273);
std::vector<int> us;
// we will use an unsorted set to avoid any duplicate values
std::unordered_set<int> values;
int count = 0;
while (count < 1000000) {
int r = std::rand() % 1000000;
if (!values.contains(r)) {
us.push_back(r);
values.emplace(r);
++count;
}
}
std::cout << "Created vector. Sorting..." << std::endl;
quicksort(us);
/* for (auto i : us) {
std::cout << i << ", ";
}
std::cout << std::endl;
*/
}