1.构造顺序表结构
#define MAXSIZE 20//顺序表的最大长度
typedef struct
{
int key;//关键字项
//可增加其他数据项
}List;//记录类型
typedef struct {
List r[MAXSIZE+1];//r[0]闲置或用作哨兵单元
int length;//顺序表长度
}SqList;
2.向顺序表中填充数据
void CreateList(SqList &L)//顺序表中填充数据
{
cout << "请输入顺序表的数据:" << endl;
L.length = 0;
int x;
int i = 1;
while (cin>>x)
{
L.r[i].key = x;
i++;
L.length++;
if (cin.get() == '\n')
{
break;
}
if (i > MAXSIZE + 1)
{
break;
}
}
}
3.顺序表的输出
void Display(SqList L)//顺序表的输出
{
cout << "顺序表:" << endl;
for (int i = 1; i <=L.length; i++)
{
cout << L.r[i].key <<" ";
}
cout << "\n";
}
4.对顺序表L的子表r[low..high]进行一趟排序,返回枢轴
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;
}
5.对顺序表的子序列L.r[low..high]进行快速排序
void Qsort(SqList& L, int low, int high)
{
//low = 1;
//high = L.length;//调用前置初值
if (low < high)
{
int pivotloc = Partition(L, low, high);//将L.r[low..high]一分为二,pivotloc是枢轴位置
Qsort(L, low, pivotloc - 1);//对左子表递归排序
Qsort(L, pivotloc + 1, high);//对右子表递归排序
}
}
6.完整代码
#include<iostream>
using namespace std;
#define MAXSIZE 20//顺序表的最大长度
typedef struct
{
int key;//关键字项
//可增加其他数据项
}List;//记录类型
typedef struct {
List r[MAXSIZE+1];//r[0]闲置或用作哨兵单元
int length;//顺序表长度
}SqList;
void CreateList(SqList &L)//顺序表中填充数据
{
cout << "请输入顺序表的数据:" << endl;
L.length = 0;
int x;
int i = 1;
while (cin>>x)
{
L.r[i].key = x;
i++;
L.length++;
if (cin.get() == '\n')
{
break;
}
if (i > MAXSIZE + 1)
{
break;
}
}
}
void Display(SqList L)//顺序表的输出
{
cout << "顺序表:" << endl;
for (int i = 1; i <=L.length; i++)
{
cout << L.r[i].key <<" ";
}
cout << "\n";
}
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)
{
//low = 1;
//high = L.length;//调用前置初值
if (low < high)
{
int pivotloc = Partition(L, low, high);//将L.r[low..high]一分为二,pivotloc是枢轴位置
Qsort(L, low, pivotloc - 1);//对左子表递归排序
Qsort(L, pivotloc + 1, high);//对右子表递归排序
}
}
void QuickSort(SqList& L)//快速排序
{
Qsort(L, 1, L.length);
cout << "快速排列后:" << endl;
Display(L);
}
int main()
{
SqList L;
CreateList(L);
Display(L);
QuickSort(L);
return 0;
}
7.运行截图
如果还有不足,请指正,感谢。