-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquick_sort.cpp
69 lines (64 loc) · 1.78 KB
/
quick_sort.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
#include <vector>
#include <iostream>
#include "print_utils.h"
template <typename T>
int Partition(std::vector<T> *collection, int lowest, int highest)
{
T mid_value = collection->at(lowest);
bool scan_direction = false; // false: right to left, true: left to right
while (lowest != highest)
{
if (scan_direction == false)
{
if (collection->at(highest) < mid_value)
{
collection->at(lowest) = collection->at(highest);
collection->at(highest) = mid_value;
scan_direction = true;
}
else
{
highest--;
}
}
if (scan_direction == true)
{
if (collection->at(lowest) > mid_value)
{
collection->at(highest) = collection->at(lowest);
collection->at(lowest) = mid_value;
scan_direction = false;
}
else
{
lowest++;
}
}
}
return lowest;
}
template <typename T>
void QuickSort(std::vector<T> *collection, int lowest, int highest)
{
if (lowest < highest)
{
int mid = Partition(collection, lowest, highest);
QuickSort(collection, lowest, mid - 1);
QuickSort(collection, mid + 1, highest);
}
}
template <typename T>
void QuickSort(std::vector<T> *collection)
{
QuickSort(collection, 0, collection->size() - 1);
}
int main(int argc, char const *argv[])
{
using namespace print_utils;
std::vector<int> data = {10, 2, 5, 2, 4, 88, 23, 34, 11, 54, 222, 3};
std::vector<int> collection = data;
std::cout << "Quick Sort:" << data << std::endl;
QuickSort(&collection);
std::cout << "Result:" << collection << std::endl;
return 0;
}