-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.cpp
More file actions
70 lines (61 loc) · 1.48 KB
/
quicksort.cpp
File metadata and controls
70 lines (61 loc) · 1.48 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
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <iterator>
using namespace std;
int bounded_rand(int max){
return rand()%max;
}
vector<int> quicksort(const vector<int> subarray){
vector<int> less;
vector<int> greater;
vector<int> result;
if(subarray.size() < 1){
return subarray;
} else {
bool equal = true;
for(int i=0; i < subarray.size(); ++i){
if(subarray[i] != subarray[0]){
equal = false;
}
}
if(equal == true){
return subarray;
}
}
int pivot = bounded_rand(subarray.size());
for(int i=0; i < subarray.size(); ++i){
if(subarray[i] <= subarray[pivot]){
less.push_back(subarray[i]);
}else{
greater.push_back(subarray[i]);
}
}
vector<int> less_sorted;
vector<int> greater_sorted;
less_sorted = quicksort(less);
greater_sorted = quicksort(greater);
result.insert(result.end(), less_sorted.begin(), less_sorted.end());
result.insert(result.end(), greater_sorted.begin(), greater_sorted.end());
return result;
}
void initialize(vector<int>& array){
for(int i=0; i<200; ++i){
array.push_back( bounded_rand(200) );
}
}
int main() {
vector<int> foo;
vector<int> bar;
initialize(foo);
bar = quicksort(foo);
stringstream input;
copy(foo.begin(), foo.end(), ostream_iterator<int>(input,", "));
stringstream output;
copy(bar.begin(), bar.end(), ostream_iterator<int>(output,", "));
std::cout << "\nInput:\n";
std::cout << input.str() <<endl;
std::cout << "\nOutput:\n";
std::cout << output.str() <<endl;
}