zoukankan      html  css  js  c++  java
  • 【书上讲解】快速排序

    描述

    【题解】

    把第一个数字作为基准,然后把[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;
    }
    
    
  • 相关阅读:
    apns libcurl
    apns libcurl
    epoll
    epoll
    Linux服务器压测
    Linux服务器压测
    libevent
    libevent
    shell脚本
    shell脚本
  • 原文地址:https://www.cnblogs.com/AWCXV/p/11620791.html
Copyright © 2011-2022 走看看