-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSorting.cpp
More file actions
41 lines (34 loc) · 1.02 KB
/
Sorting.cpp
File metadata and controls
41 lines (34 loc) · 1.02 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
#include <vector>
#include <algorithm>
#include "iostream"
// Select pivot, shuffle it around and return the pivot index
int selectAndShuffle(std::vector<int>& a, int begin, int end) {
int pivotValue = a[begin]; // pick first index as pivot. Can also pick any arbitrary index and swap it with the first element
int current = begin;
for (int i=begin+1; i<=end; i++) {
if (a[i] < pivotValue) {
current++;
std::swap(a[current], a[i]);
}
}
std::swap(a[begin], a[current]);
return current;
}
void qsort(std::vector<int>& a, int begin, int end) {
int pivotIndex = selectAndShuffle(a, begin, end);
if (pivotIndex - 1 > begin) {
qsort(a, begin, pivotIndex-1);
}
if (pivotIndex + 1 < end) {
qsort(a, pivotIndex+1, end);
}
return;
}
int main() {
std::vector<int> toSort = {1,4,5,2,3,-1,0};
qsort(toSort, 0, toSort.size()-1);
for (int i=0; i<toSort.size(); i++) {
std::cout << toSort[i] << std::endl;
}
return 0;
}