快速排序c语言程序

#include<stdio.h>
#define MAXSIZE 20//顺序表的最大长度
#define LT(a,b) ((a)<(b))
typedef int KeyType;//定义关键字的类型为整型
typedef char InfoType;//定义其他信息为字符类型


typedef struct
{
    KeyType key;//关键字项
    InfoType otherinfo;//其他数据项
}RedType;


typedef struct
{
    RedType r[MAXSIZE+1];//r[0]闲置或作为监视哨
    int length;//顺序表长度
}SqList;


int ptime=0;//划分序列的次数
void print(SqList &L)
{
    int i;
    for(i=1;i<=L.length;i++)
       printf("%-3d",L.r[i].key);
    printf("\n");
}
//对L.r[low...high]做划分,使枢轴记录到位,并返回其位置
int Partition(SqList &L,int low,int high)
{
    int pivotkey;
    L.r[0]=L.r[low];
    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];
    ptime++;
    printf("第%d次划分排序为:",ptime);
    print(L);
    return low;
}
//递归法对L中的序列做快速排列
void Qsort(SqList &L,int low,int high)
{
    int pivotloc;
    if(low<high)
    {
        pivotloc=Partition(L,low,high);
        Qsort(L,low,pivotloc-1);
        Qsort(L,pivotloc+1,high);
    }
}


 int main()
 {
     int i;
     SqList L;
     printf("输入要排序的列表长度n:");
     scanf("%d",&L.length);
     for(i=1;i<=L.length;++i)
     {
         printf("输入第%d个记录的关键字;",i);
         scanf("%d",&L.r[i].key);
     }
     printf("初始关键字为:");
     print(L);
     Qsort(L,1,L.length);
     printf("快速排序后的记录为:");
     print(L);
 }

猜你喜欢

转载自blog.csdn.net/qq_38452951/article/details/80499460
今日推荐