数据结构之快速排序
参考书籍:严蔚敏《数据结构》
参考视频:李春葆《数据结构》
https://www.icourse163.org/learn/WHU-1001539003?tid=1002049010#/learn/content?type=detail&id=1002711947&sm=1
测试代码:
//希尔排序
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
typedef struct{ //记录类型
int key; //关键字
char data; //数据
}record;
typedef struct{
record rec[MAXSIZE+1]; //包含MAXSIZE+1个记录,记录0是哨兵,相当于tmp
int length; //顺序表的长度
}sqList;
int partition(sqList *L,int low,int high);
void qSort(sqList *L,int low,int high);
int main()
{
sqList L;
L.length = MAXSIZE;
//使用随机数据初始化sqList中的数据
for(int i = 1;i<=L.length;i++)
{
L.rec[i].key = rand()%23;
L.rec[i].data = 'a' + L.rec[i].key;
}
//输出排序前的记录
for(int i = 1;i<=L.length;i++)
printf("record %2d: key = %2d, data = %c\n",i,L.rec[i].key,L.rec[i].data);
//快速排序
qSort(&L,1,L.length);
//输出排序后的记录
printf("\n------>希尔排序后<------\n");
for(int i = 1;i<=L.length;i++)
printf("record %2d: key = %2d, data = %c\n",i,L.rec[i].key,L.rec[i].data);
return 1;
}
//快速排序分区函数
int partition(sqList *L,int low,int high)
{
record privotkey;
L->rec[0] = L->rec[low];
privotkey.key = L->rec[low].key;
while(low<high)
{
while(low<high && L->rec[high].key>=privotkey.key) --high;
L->rec[low] = L->rec[high];
while(low<high && L->rec[low].key<=privotkey.key) ++low;
L->rec[high] = L->rec[low];
}
L->rec[low] = L->rec[0];
return low;
}
//快速排序
void qSort(sqList *L,int low,int high)
{
record privotloc;
if(low<high)
{
privotloc.key = partition(L,low,high);
qSort(L,low,privotloc.key-1);
qSort(L,privotloc.key+1,high);
}
}
测试结果:
record 1: key = 18, data = s
record 2: key = 21, data = v
record 3: key = 9, data = j
record 4: key = 4, data = e
record 5: key = 10, data = k
record 6: key = 15, data = p
record 7: key = 1, data = b
record 8: key = 10, data = k
record 9: key = 6, data = g
record 10: key = 15, data = p
record 11: key = 1, data = b
record 12: key = 16, data = q
record 13: key = 5, data = f
record 14: key = 14, data = o
record 15: key = 2, data = c
record 16: key = 8, data = i
record 17: key = 5, data = f
record 18: key = 5, data = f
record 19: key = 20, data = u
record 20: key = 8, data = i
------>快速排序后<------
record 1: key = 1, data = b
record 2: key = 1, data = b
record 3: key = 2, data = c
record 4: key = 4, data = e
record 5: key = 5, data = f
record 6: key = 5, data = f
record 7: key = 5, data = f
record 8: key = 6, data = g
record 9: key = 8, data = i
record 10: key = 8, data = i
record 11: key = 9, data = j
record 12: key = 10, data = k
record 13: key = 10, data = k
record 14: key = 14, data = o
record 15: key = 15, data = p
record 16: key = 15, data = p
record 17: key = 16, data = q
record 18: key = 18, data = s
record 19: key = 20, data = u
record 20: key = 21, data = v
--------------------------------
Process exited after 0.1219 seconds with return value 1
请按任意键继续. . .

浙公网安备 33010602011771号