zoukankan      html  css  js  c++  java
  • 快速排序原理

    快速排序

    排序在各种场合经常被用到。
    快速排序是十分常用的高效率的算法。

    其思想是:先选一个“标尺”,
    用它把整个队列过一遍筛子,
    以保证:其左边的元素都不大于它,其右边的元素都不小于它。

    这样,排序问题就被分割为两个子区间。
    再分别对子区间排序就可以了。

    #include<iostream>
    #include<stdio.h>
    #include<algorithm>
    using namespace std;
    typedef long long LL;
    const int maxn=1e4+5;
    int a[maxn];
    int N;
    LL ans=0;
    int Find(int l,int r)
    {
        int x=a[l];
        int i=l;
        int j=r+1;
        while(1)
        {
            while(a[++i]<x&&i<=r) ;//找到第一个大于x的数
            while(a[--j]>x&&j>=l) ;//找到第一个小于x的数
            if(i>=j) break;
            ans++;
            swap(a[i],a[j]);
        }
        if(j>l)
        {
            ans++;
            swap(a[l],a[j]);
        }
    
        return j;
    }
    void quicksort(int l,int r)
    {
        //int p=l;
        if(l<r)
        {
            int p=Find(l,r);
            quicksort(l,p-1);
            quicksort(p+1,r);
        }
        return ;
    }
    int main()
    {
        scanf("%d",&N);
        for(int i=0;i<N;i++) scanf("%d",&a[i]); 
    
        quicksort(0,N-1);
        printf("%lld
    ",ans);
        return 0;
    }
    int split(int a[],int low,int high)
    {
        //以最左边的元素为基准
        int i=low;
        int x=a[low];
        for(int j=low+1;j<=high;j++) //遍历一遍
        {
            //将小于x的元素往前挪
            if(a[j]<=x) //
            {
                i++;
                swap(a[i],a[j]);
            }
        }
        //此时在low+1到i位置所有元素都小于等于low所在的位置  i+1到high都大于low所在的位置
        swap(a[i],a[low]);//将low换到期待的位置
        return i;
    }
    void Quick_sort(int a[],int low,int high)
    {
        if(low<high)
        {
            int i=split(a,low,high);
            Quick_sort(a,low,i-1);
            Quick_sort(a,i+1,high);
        }
    }
    当初的梦想实现了吗,事到如今只好放弃吗~
  • 相关阅读:
    hdu6229 Wandering Robots 2017沈阳区域赛M题 思维加map
    hdu6223 Infinite Fraction Path 2017沈阳区域赛G题 bfs加剪枝(好题)
    hdu6438 Buy and Resell 买卖物品 ccpc网络赛 贪心
    hdu6441 Find Integer 求勾股数 费马大定理
    bzoj 1176 Mokia
    luogu 3415 祭坛
    bzoj 1010 玩具装箱
    bzoj 3312 No Change
    luogu 3383【模板】线性筛素数
    bzoj 1067 降雨量
  • 原文地址:https://www.cnblogs.com/caijiaming/p/10502774.html
Copyright © 2011-2022 走看看