#include "stdafx.h"
#include <iostream.h>
#include <malloc.h>

int const count=8;

typedef struct


{
int key;
}records;

typedef records list[count+1];

//此处没有使用书中的算法,书中的算法实现很繁索,且使用i,h,j,p,x一类的变量,使程序阅读更加吃力
//我实现的是严蔚敏版的数据结构中关于快速排序的算法,但书中的算法和这个思路是一致的,不过在于一些判断的时候方法有些不同,也没有这个算法巧妙
//快排算法最核心的思路就是,在一个排序数据中,取一个值,然后将小于它的数组项放在左面,将大于它的数组项放在它的右边,
//而这个值就是中值,然后分别再对分开的两部分再次调用排序算法,直至排序完成.
//r:排序的数组 low:排序区域中小的索引 high:排序区域中大的索引 return:分割两部分的中点索引
int Partition(list & r,int low,int high)


{
r[0].key=r[low].key;
while(low<high)

{
while(low<high && r[high].key>=r[0].key)

{
high--;
}
//这里覆盖了low的值,这个值在首次的时候被r[0]所复制,在其它的时候,这个值属于在上次循环时确定的可以存放大于"枢轴值"的点位置
r[low].key=r[high].key;
while(low<high && r[low].key<=r[0].key)

{
low++;
}
//这里覆盖了high的值,这个值是在上面的循环中确定的可以存放小于"枢轴值"的点的位置
r[high].key=r[low].key;
}
r[low].key=r[0].key;
return low;
}

//快速排序
void QuickSort(list & r,int low,int high)


{
if (low<high)

{
//得到中值的索引
int pivotkey=Partition(r,low,high);
//递归排序此中值左边的数组项
QuickSort(r,low,pivotkey-1);
//递归排序此中值右边的数组项
QuickSort(r,pivotkey+1,high);
}
}

void printList(list r)


{
for(int i=0;i<count;i++)

{
if (i==0)

{
cout<<r[i+1].key;
}
else

{
cout<<","<<r[i+1].key;
}
}
cout<<endl;
}

int main(int argc, char* argv[])


{
list r;

/**//*
for(int i=0;i<count;i++)
{
cout<<"输入第"<<i+1<<"个主键";
cin>>r[i+1].key;
}
*/
r[1].key=70;
r[2].key=73;
r[3].key=69;
r[4].key=23;
r[5].key=93;
r[6].key=18;
r[7].key=11;
r[8].key=68;
cout<<"输入的序列为:"<<endl;
printList(r);
QuickSort(r,1,count);

cout<<"快速排序后的序列为:"<<endl;
printList(r);
return 0;
}
一点说明:为什么在标题中要嵌入英文?原因是为了能够让国外的网友能查询到这篇文章。平常在Google上查资料的时候,经常参考国外网友的博客,帮助我解决了很多问题,所以我也想让他们能够参考我写的内容。当然文中我不可能全部译为英文,所以我尽量把代码粘全,靠代码说话吧。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步