码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2019-03-04 11:21:23      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:void   scan   递归   编译器   name   return   max   swap   space   


#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 1e5 + 5;                   //100005
int a[maxn], n;
                                            //写法1,推荐使用写法2 
void QuickSort(int s, int t)                //慎用 inline,大多数编译器不支持递归函数的内联(inline) 
{
    int l=s, r=t, mid=a[(l+r)>>1];
    while(l<=r)                             //<= 
    {
        while(a[l]<mid) l++;                //必须是<,不能把等于mid的跳过 
        while(a[r]>mid) r--;                //必须是> 
        if(l<=r)
            swap(a[l], a[r]), l++, r--;
    }
    if(s<r) QuickSort(s, r);
    if(l<t) QuickSort(l, t);
    return;
}
                                            //写法2,推荐使用此写法 
void QuickSort2(int s, int t)
{
    int pivot=a[s], l=s, r=t;
    while(l<r)
    {
        while(l<r && a[r]>=pivot)   r--;    //>= 拆东补西,必须把等于pivot的跳过 
        a[l]=a[r];
        while(l<r && a[l]<=pivot)   l++;    //<= 拆西补东 
        a[r]=a[l];
    }
    a[l]=pivot;                             //添入哨兵 
    if(s<l-1)   QuickSort2(s, l-1);
    if(l+1<t)   QuickSort2(l+1, t); 
} 
int main(void)
{
    scanf("%d", &n);
    for(int i=1; i<=n; i++)     scanf("%d", &a[i]);
    QuickSort(1, n);
    for(int i = 1; i <= n; i++) printf("%d ", a[i]);
    return 0;
}

快速排序

标签:void   scan   递归   编译器   name   return   max   swap   space   

原文地址:https://www.cnblogs.com/lfyzoi/p/10469531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!