教材:严版数据结构

页码:P272-276

实现:算法10.6-10.8

代码如下:

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<iostream>

using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define MAXSIZE 20
#define LT(a,b) (a<b)
#define EQ(a,b) (a==b)

typedef int Status;
typedef int KeyType;
typedef int InfoType;
typedef struct {
KeyType key;//关键字项
InfoType otherinfo;//其他数据项
}RedType;

typedef struct {
RedType r[MAXSIZE + 1];//r[0]闲置或用作哨兵单位
int length;//顺序表长度
}SqList;//顺序表类型

Status InitList(SqList &L)
{
//构造一个空的顺序表L
L.length = 0;//空表长度为0
return OK;
}
//创建n个元素的顺序表
Status CreateList(SqList &L, int n)
{
int i;
cout << "输入" << n << "个元素" << endl;
for (i = 1; i <= n; i++)
{
cin >> L.r[i].key;
++L.length;
}
if (L.length == 0)
return ERROR;//创建失败
return OK;
}
//输出顺序表
Status DispList(SqList &L)
{
int i;
if (L.length == 0)
return ERROR;
for (i = 1; i <= L.length; i++)
{
cout << L.r[i].key << " ";
}
cout << endl;
return OK;
}
//找到位置
int Partition(SqList &L, int low, int high)
{
L.r[0] = L.r[low];
int pivotkey = L.r[low].key;
while (low < high)
{
while (low < high&&L.r[high].key >= pivotkey)
--high;
L.r[low] = L.r[high];
while (low < high&&L.r[low].key <= pivotkey)
++low;
L.r[high] = L.r[low];
}
L.r[low] = L.r[0];
return low;
}
//递归排序
void QSort(SqList &L, int low, int high)
{
if (low < high)
{

int pivotloc = Partition(L, low, high);
QSort(L, low, pivotloc - 1);//对底子表递归排序
QSort(L, pivotloc + 1, high);//对高子表递归排序
}
}

void QuickSort(SqList &L)
{
QSort(L, 1, L.length);
}


void main()
{
SqList L;
int n;
cout << "初始化顺序表,";
InitList(L);
if (L.length == 0)
cout << "顺序表为空!\n";
cout << "输入顺序表的元素个数:";
cin >> n;
CreateList(L, n);
cout << "输出" << n << "个元素的顺序表如下:" << endl;
DispList(L);
QuickSort(L);
cout << "快速排序结果如下:" << endl;
DispList(L);
system("pause");
}