-
Notifications
You must be signed in to change notification settings - Fork 0
/
快速排序算法.c
111 lines (78 loc) · 2.4 KB
/
快速排序算法.c
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
111
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int Partition (int r[], int low , int high )
{
//交换顺序表L中子表r high的记录 枢轴记录到位,并返回其所在的位置,
//此时在它之前 (后)的记录均不大(小)于它
int cache;
int pivotkey;
cache = r[low];
pivotkey = r[low]; //用子表的第一个记录作枢轴记录
while (low < high) //从表的两段交替向中间扫描
{
while ((low < high) && (r[high] >= pivotkey))
{
high--; //比枢轴记录小的移到低端
}
r[low] = r[high];
while ((low < high) && (r[low] <= pivotkey))
{
low++;//比枢轴记录大的移到高端
}
r[high] = r[low];
}
r[low] = cache;
r[low] = pivotkey;
return low ; //返回枢轴位置
}
void QSort (int L, int low, int high)
{
int pivotloc = 0;
//对顺序表L中 子序列 low high 做快速排序
if (low < high) //长度大于一
{
pivotloc = Partition(L, low, high); //将L一分为二
QSort(L, low, pivotloc - 1); //对低子表递归排序
QSort(L, pivotloc + 1, high); //对高子表递归排序
}
}
void QuickSort(int L[], int len)
{
//对顺序表L 做快速排序
// printf (" len=%d ", len);
QSort(L, 0, len);
}
int main()
{
int a[50] = {0};
int i;
int len;
for (i = 0; i < 30; i++)
{
// a[i] = i * i * i - 20 * i * i + 10 * i + 20;
a[i] = 60 - i * 2;
}
for (i = 0; i < 30; i++)
{
if (i % 5 == 0)
{
printf("\n");
}
printf (" %d ", a[i]);
}
printf("\n");
len = 29;
QuickSort (a, len);
printf (" \n");
for (i = 0; i < 30; i++)
{
if (i % 5 == 0)
{
printf("\n");
}
printf (" %d ", a[i]);
}
printf("\n\n");
return 0;
}