-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquicksort.cpp
More file actions
70 lines (57 loc) · 1.32 KB
/
Copy pathquicksort.cpp
File metadata and controls
70 lines (57 loc) · 1.32 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
/*
* @Author: five-5
* @Description:
* @Date: 2019-03-24
* @LastEditTime: 2019-03-24
*/
#include <iostream>
using std::cout;
using std::endl;
template <typename T, size_t len>
void QuickSortImp(T (&arr)[len], size_t first, size_t last) {
if (first >= last) {
return;
}
size_t low = first;
size_t high = last;
T key = arr[first];
while (first < last) {
while (first < last && arr[last] >= key) {
--last;
}
if (first < last) {
arr[first++] = arr[last];
}
while (first < last && arr[first] <= key) {
++first;
}
if (first < last) {
arr[last--] = arr[first];
}
}
arr[first] = key;
QuickSortImp(arr, low, first - 1);
QuickSortImp(arr, first + 1, high);
}
template <typename T, size_t len>
void QuickSort(T (&arr)[len]) {
QuickSortImp(arr, 0, len - 1);
}
// print
template <typename T>
void print(T *begin, T *end) {
for (auto it = begin; it != end; ++it) {
cout << *it << " ";
}
cout << endl;
}
int main()
{
int arr[] = {1, 3, 9, 5, 0};
cout << "original arr : " << endl;
print(std::begin(arr), std::end(arr));
QuickSort(arr);
cout << "after sort arr by basic: " << endl;
print(std::begin(arr), std::end(arr));
return 0;
}