数据结构-快速排序

程序代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 20
typedef int KeyType;
typedef char InfoType;

//结构体定义
typedef struct {
    KeyType key;
    InfoType otherinfo;
}RedType;
typedef struct {
    RedType r[MAXSIZE+1];
    int length;
}SqList;

//各个函数定义
void print(SqList *L);
void init(SqList *L);
int Partition(SqList *L,int low,int high);
void QSort(SqList *L,int low,int high);
void QuickSort(SqList *L);

//初始化,随机产生待排序的数组
void init(SqList *L) {
    int n,i;
    printf("请输入待排序的元素个数:");
    scanf("%d",&n);
    srand(((int)time(0)));//设置随机种子
    for(i=1; i<=n; i++) {
        L->r[i].key = rand()%10+1;
    }
    L->length = n;
    printf("随机产生的待排数组为:");
    print(L);
    printf("\n");
}

//输出数组元素
void print(SqList *L) {
    int i;
    for(i=1; i<=L->length; i++) {
        printf("%d ",L->r[i].key);
    }
    printf("\n");
}

//进行分趟排序
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];
    return low;
}
/*int Partition(SqList *L,int low,int high) {
    int pivotkey;
    pivotkey = L->r[low].key;
    while(low<high) {
        while(low<high && L->r[high].key>=pivotkey) {
        --high;
        }
        L->r[0] = L->r[high];
        L->r[high] = L->r[low];
        L->r[low] = L->r[0];
        while(low<high && L->r[low].key<=pivotkey) {
            ++low;
        }
        L->r[0] = L->r[high];
        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 = Partition(L,low,high);
        QSort(L,low,pivotloc-1);
        QSort(L,pivotloc+1,high);
    }
}

//进行快速排序
void QuickSort(SqList *L) {
    QSort(L,1,L->length);
}

//主函数
int main()
{
    SqList sq;
    int k;
    init(&sq);
    QuickSort(&sq);
    printf("排序之后的数组为:");
    print(&sq);
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值