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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
|
#include
#include
#include
void
Swap(
int
arr[],
int
a1,
int
a2) {
int
tmp = arr[a1]; arr[a1] = arr[a2]; arr[a2] = tmp; }
void
Gather(
int
arr[],
int
low,
int
high,
int
pos,
int
*left,
int
*right) {
if
(low < high) {
int
count = pos-
1
;
for
(
int
i = pos-
1
; i >= low; i--) {
if
(arr[i] == arr[pos]) { Swap(arr, i, count); count--; } } *left = count;
int
num = pos+
1
;
for
(
int
j = pos+
1
; j <= high; j++) {
if
(arr[j] == arr[pos]) { Swap(arr, j, num); num++; } } *right = num; } }
int
Partion(
int
arr[],
int
low,
int
high)
//具体分成一部分比另一部分大的排序
{
int
tmp = arr[low];
while
(low < high) {
while
(low<=arr[high]) high--; arr[low] = arr[high];
while
(low=arr[low]) low++; arr[high] = arr[low]; } arr[low] = tmp;
return
low; }
void
TakeSecondMaxnum(
int
arr[],
int
low,
int
mid,
int
high)
//三分取中法
{
if
(arr[mid] < arr[high]) { Swap(arr, mid, high); }
if
(arr[low] < arr[high]) { Swap(arr, low, high); }
if
(arr[low] < arr[mid]) { Swap(arr, low, mid); } }
void
InsertSort(
int
arr[],
int
low,
int
high)
//优化一数据量小时,不适宜使用快排,而用插入排序更好
{
int
i, j;
for
(i =
2
; i < high-low+
1
; ++i) { arr[
0
] = arr[i];
for
(j = i -
1
; arr[j] > arr[
0
]; --j) { arr[j +
1
] = arr[j]; } arr[j +
1
] = arr[
0
]; } }
void
Sort(
int
arr[],
int
low,
int
high) {
if
(low < high) { Swap(arr, low, rand()%(high-low)+low);
// 优化二,在最坏情况全部有序时交换基准点
TakeSecondMaxnum(arr, low, (high-low)/
2
+low, high);
//优化三,基准点选取“中数”
int
pos = Partion(arr, low, high);
int
left = pos-
1
;
int
right = pos+
1
; Gather(arr, low, high, pos, &left, &right);
//优化四,聚集与基准点相同的元素,这些元素不参加之后排序
Sort(arr, low, left); Sort(arr, right, high); } }
void
QuickSort(
int
arr[],
int
len) { Sort(arr,
0
, len-
1
); }
int
main() {
int
a[] = {
2
,
3
,
1
,
6
,
5
,
4
,
9
,
8
,
7
,
0
,
21
,
34
,
32
,
27
,
87
,
56
,
43
,
48
,
76
,
29
,
55
};
int
len =
sizeof
(a)/
sizeof
(a[
0
]); QuickSort(a, len);
for
(
int
i =
0
; i < len; i++) { printf(
"%d "
,a[i]); } printf(
"\n"
); }
|