排序——快速排序

##快速排序
这里总结两种快速排序方法

  • 冒泡排序
  • 快速排序

冒泡排序

思想就是:相邻两个记录进行比较,交换,依次进行直到有序。每一趟都是把剩余最大的元素排到序列的最后。
举例:

有一序列为:
初始态: 5 4 6 8 7 2 3
第一趟: 4 5 6 7 2 3 8
第二趟: 4 5 6 2 3 7 8
第三趟: 4 5 2 3 6 7 8
第四趟: 4 2 3 5 6 7 8
第五趟: 2 3 4 5 6 7 8
/*
    BubbleImplementation
    Author:zzj
    Date:17-6-17
*/
#include<cstdio> 
using namespace std;
const int maxn = 100;
int a[maxn];
int n;

void BubbleSort(int *a)
{
    int ok;
    for(int i=0; i<n; i++)
    {
        ok = 1;
        for(int j=0; j<n-1; j++)
        {
            if(a[j] > a[j+1])//前后比较 
            {
                int t = a[j];
                a[j] = a[j+1];
                a[j+1] = t; //交换 
                ok = 0;
            } 
        }
        if(ok) break;//如果没有交换则已排序好,直接退出
    }
}

int main()
{
    scanf("%d", &n);
    for(int i=0; i<n; i++)
    {
        scanf("%d", &a[i]);
    }
    BubbleSort(a);
    for(int i=0; i<n; i++)
        printf("%d ",a[i]);
    return 0;
}

快速排序

它是对冒泡排序的一种改进。
基本思想:通过一趟排序将带排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小。
举例:

有一序列为:
初始态: 5 4 6 8 7 2 3 选择5为枢轴
        3 4 2 5 7 8 6 前一半选择3为枢轴
        2 3 4 5 7 8 6 后一半选择7为枢轴
        2 3 4 5 6 7 8
/*
    QuickSort Implementation
    Author:zzj
    Date:17-6-17
*/
#include<cstdio> 
using namespace std;
const int maxn = 100;
int a[maxn];
int n;
/*交换数组a中子表a[low..high]的记录,枢轴记录到位,并返回其所在位置*/
int Partition(int *a, int low, int high)
{
    int pivotkey;//枢轴
    a[0] = a[low];//用子表的第一个记录作枢轴 
    pivotkey = a[low];//枢轴记录关键字 
    while(low < high)//从表的两端交替地向中间扫描 
    {
        while(low < high && a[high] >= pivotkey) --high;
        a[low] = a[high];//将比枢轴记录小的记录移到低端 
        while(low < high && a[low] <= pivotkey) ++low;
        a[high] = a[low];//将比枢轴记录大的记录移到高端 
    }
    a[low] = a[0];//枢轴记录到位 
    return low;   //返回枢轴位置 
}
/*对数组a[low..high]进行快速排序*/
void QSort(int *a, int low, int high) 
{
    if(low < high)
    {
        int pivotloc = Partition(a, low, high);//将a[low..high]一分为二 
        QSort(a, low, pivotloc-1); //对低子表递归排序 
        QSort(a, pivotloc+1, high);//对高子表递归排序 
    }
}

void QuickSort(int *a)
{
    QSort(a, 1, n);
}

int main()
{
    scanf("%d", &n);
    for(int i=1; i<=n; i++)
    {
        scanf("%d", &a[i]);
    }
    QuickSort(a);
    for(int i=1; i<=n; i++)
        printf("%d ",a[i]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值