C语言快速排序

#include<stdio.h>

#include<stdlib.h>

#define MAX_SIZE 20

// 给int类型起个别名
typedef int KeyType;
typedef int InfoType;



typedef struct RedType
{
    KeyType key;

    InfoType otherinfo;

}RedType;



typedef struct OrderList
{
    RedType R[ MAX_SIZE + 1 ];

    int length;

}OrderList;



/*
 * 一趟快速排序
 */
int Partition(OrderList *L, int low, int high)
{
    // 枢纽
    KeyType pivot_key;

    // 以子表的首记录作为枢纽,放入R[0]单元
    L->R[0] = L->R[low];

    // 取枢纽值存入pivot_key变量
    pivot_key = L->R[low].key;


    while( low < high )
    {
        while( low < high && L->R[high].key >= pivot_key)
            high--;

        // 将比枢纽小的记录交换到低端
        L->R[low] = L->R[high];

        while( low < high && L->R[low].key <= pivot_key)
            low++;

        //将比枢纽大的记录交换到高端
        L->R[high] = L->R[low];

    }

    // 枢纽到位,现在枢纽元素左边都是比它小的,右边都是比它大的
    L->R[low] = L->R[0];

    // 返回枢纽元素所在位置
    return low;

}



/*
 *  快速排序的递归算法
 */
void QuickSort(OrderList *L, int i, int j)
{
    int pivot_loc;

    // 对顺序表L中的子序列R[i,...,j]作快排
    if( i < j)
    {
        // 一趟快速排序将R[i,...,j]一分为二
        pivot_loc = Partition(L, i, j);

        // 在左子区间进行递归快排,直到区间长度为1
        QuickSort(L, i, pivot_loc-1);

        // 在右子区间进行递归快排,直到区间长度为1
        QuickSort(L, pivot_loc+1, j);
    }

}




int main()
{
    OrderList *L;

    L = (OrderList *)malloc( sizeof( OrderList ) );


    int i, j ;

    printf("需要排序的元素个数为:");

    scanf("%d", &L->length);


    printf("\nPlease input the element: ");

    for(i = 0; i < L->length; i++)
    {
        scanf("%d", &L->R[i+1].key);
    }


    QuickSort(L, 1, L->length);


    printf("\n快排后序列为:");
    for(j = 1; j <= L->length; j++)
    {
        // -2,输出结果左对齐,提供2个字符的空间用于输出a

        printf("%-2d", L->R[j].key);
    }

    printf("\n");
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值