-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cpp
More file actions
41 lines (36 loc) · 947 Bytes
/
Copy pathQuickSort.cpp
File metadata and controls
41 lines (36 loc) · 947 Bytes
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
#include <iostream>
#include <vector>
std::pair<int, int> partition3(std::vector<int>& nums, int l, int r) {
int pivot = l + rand() % (r - l + 1);
int p = nums[pivot];
std::swap(nums[pivot], nums[r]);
int lt = l, i = l, gt = r - 1;
while(i <= gt) {
if (nums[i] < p) {
std::swap(nums[i++], nums[lt++]);
} else if (nums[i] > p) {
std::swap(nums[i], nums[gt--]);
} else {
i++;
}
}
std::swap(nums[i], nums[r]);
return {lt, i};
}
void quickSort(std::vector<int>& nums, int l, int r) {
if (l >= r) {
return;
}
auto p = partition3(nums, l, r);
// +1, -1
quickSort(nums, l, p.first - 1);
quickSort(nums, p.second + 1, r);
return;
}
int main () {
std::vector<int> vec = {1, 2, 3, 7, 9, 1, 4, 6, 9};
quickSort(vec, 0, vec.size() - 1);
for (auto each : vec) {
std::cout << each << ", ";
}
}