您的位置:首页 > 编程语言 > C语言/C++

快速排序C语言算法实现

2011-06-04 22:56 711 查看
#include "stdio.h"
#include "stdlib.h"
typedef struct
{
int key;
}Record;
typedef struct
{
Record *r;
int length;
}SqList;

void Display(SqList L)
{
for(int i=1;i<L.length+1;i++)
printf("%d ",L.r[i].key);
printf("/n");
}

int Partion(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)
{
int pivotloc;
if (low<high)
{
pivotloc=Partion(L,low,high);
QSort(L,low,pivotloc-1);
QSort(L,pivotloc+1,high);
}
}

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

void CreateSqList(SqList &L)
{
printf("Please input the number of data:/n");
scanf("%d",&L.length);
L.r=(Record*)malloc((L.length+1)*sizeof(Record));
printf("please input data:/n");
for(int i=1;i<=L.length;i++)
scanf("%d",&L.r[i].key);
L.r[0].key=0;//0号未用元素初始化为0
}

void main()
{
SqList L;
CreateSqList(L);
Display(L);
QuickSort(L);
Display(L);
}


输入输出如下:

Please input the number of data:
8
please input data:
49 38 65 97 76 13 27 49
49 38 65 97 76 13 27 49
13 27 38 49 49 65 76 97
Press any key to continue

如有不足请多指教!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: