[Book] to explain the quick sort

description

【answer】


The first number as a reference, and then [l + 1, r] be divided.
Found largest j, such that a [j] <= x, i.e., j + 1..r is greater than x
and j is this time division result
added in front of each template function After you can substitute any type with the Type (passed in anything can be)

[Code]

#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;
}

Guess you like

Origin www.cnblogs.com/AWCXV/p/11620791.html