严版数据结构P272-276
算法10.6-10.8
代码如下:
#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");
}