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

    
    #include<iostream>
    #include<cstdio>
    using namespace std;
    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;
    }
    
    
  • 相关阅读:
    Python标准模块--logging
    Spark中决策树源码分析
    常见的相似或相异程度计算方法
    mpi4py实践
    集成学习
    决策树
    git使用
    Ubuntu 14.04 64bit 安装tensorflow(GPU版本)
    KNN算法
    一致性哈希算法原理及其在分布式系统中的应用
  • 原文地址:https://www.cnblogs.com/lfyzoi/p/10469531.html
Copyright © 2011-2022 走看看