-
Notifications
You must be signed in to change notification settings - Fork 1
/
QuickSort.cpp
85 lines (75 loc) · 1.28 KB
/
QuickSort.cpp
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
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
// data index range [low, high]
int Partition(vector<int> & vec, int low, int high)
{
int priovt = vec[high];
int i = low - 1;
for (int j = low; j < high; ++j)
{
if (vec[j] < priovt)
{
swap(vec[++i], vec[j]);
}
}
swap(vec[++i], vec[high]);
return i;
}
// data index range [low, high]
void QuickSort(vector<int> & vec, int low, int high)
{
if (low < high)
{
int mid = Partition(vec, low, high);
QuickSort(vec, low, mid - 1);
QuickSort(vec, mid + 1, high);
}
}
void QuickSortIterator(vector<int> & vec, int low, int high)
{
if (low < high)
{
stack<int> sta;
sta.push(low);
sta.push(high);
while (!sta.empty())
{
int right = sta.top();
sta.pop();
int left = sta.top();
sta.pop();
int mid = Partition(vec, left, right);
if (left < mid - 1)
{
sta.push(left);
sta.push(mid - 1);
}
if (mid + 1 < right)
{
sta.push(mid + 1);
sta.push(high);
}
}
}
}
int main()
{
vector<int> vec;
vec.reserve(32);
for (int i = 10; 0 < i; --i)
{
for (int j = 2; 0 < j; --j)
{
vec.push_back(i);
}
}
//QuickSort(vec, 0, vec.size() - 1);
QuickSortIterator(vec, 0, vec.size() - 1);
for (int item : vec)
{
cout << item << " ";
}
cout << endl;
}