-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathquick_sort.cpp
More file actions
53 lines (45 loc) · 979 Bytes
/
quick_sort.cpp
File metadata and controls
53 lines (45 loc) · 979 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
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Author: Skylar Payne
* Date: January 7, 2015
* Implement quick-sort in place
**/
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <assert.h>
void qsort(std::vector<int>& a, int low = 0, int high = -1) {
if(high == -1) {
high = a.size() - 1;
}
if(high <= low) {
return;
}
int piv = rand() % (high - low + 1) + low;
int swap_ind = 0;
std::swap(a[piv], a[high]);
for(int i = 0; i < high; ++i) {
if(a[i] < a[high]) {
std::swap(a[i], a[swap_ind++]);
}
}
std::swap(a[high], a[swap_ind]);
qsort(a, low, swap_ind);
qsort(a, swap_ind+1, high);
}
int main(int argc, char** argv) {
if(argc < 2) {
std::cout << "Please provide a list of integers to sort" << std::endl;
return -1;
}
std::vector<int> a(argc - 1);
for(int i = 1; i < argc; ++i) {
a[i-1] = atoi(argv[i]);
}
qsort(a);
for(int i = 1; i < a.size(); ++i) {
assert(a[i-1] <= a[i]);
}
std::cout << "Sorted" << std::endl;
return 0;
}