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

【书上讲解】快速排序

时间:2019-10-03 22:11:46      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:name   font   i++   ace   描述   using   art   swa   mes   

描述

【题解】


把第一个数字作为基准,然后把[l+1,r]进行划分.
找到最大的j,使得a[j]<=x,即j+1..r都是大于x的
然后j就是这次划分的结果
在每个函数前面加template 之后就能用Type代替任意类型了(传进来什么都可以)

【代码】

#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 1e5;

int n;
int a[N+10];



template <class Type>
int _partition(Type a[],int l,int r){
    int i = l,j = r+1;
    Type x = a[l];
    while (i<j){
        while (a[++i]<x && i<r);//a[i]最后>=x
        while (a[--j]>x);
        if (i>=j) break;
        swap(a[i],a[j]);
    }
    //a[j]最后<=x,且j是最大的满足a[j]<=x的j
    a[l] = a[j];
    a[j] = x;
    return j;
}

template <class Type>
void QuickSort(Type a[],int l,int r){
    int index = _partition(a,l,r);
    if (l<index) QuickSort(a,l,index-1);
    if (index<r) QuickSort(a,index+1,r);
}

int main(){
    //freopen("D:\\rush.txt","r",stdin);
    scanf("%d",&n);
    for (int i = 1;i <= n;i++){
        scanf("%d",&a[i]);
    }
    QuickSort(a,1,n);
    for (int i = 1;i <= n;i++) printf("%d ",a[i]);
    return 0;
}

【书上讲解】快速排序

标签:name   font   i++   ace   描述   using   art   swa   mes   

原文地址:https://www.cnblogs.com/AWCXV/p/11620791.html

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