POJ 2388 Who's in the Middle (快速排序)

给一组数列,找中间数,写了个快速排排序,用时92ms, 然后干脆直接用STL的排序O(nlogn)用时34ms,虽然两者都为O(nlogn),STL确实快呀。当然做这题的目的还是分治的运用,留代码在此。

#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<sstream>
#include<cmath>
#include<iterator>
#include<bitset>
#include<stdio.h>
#include<time.h>
using namespace std;
#define _for(i,a,b) for(int i=(a);i<(b);++i)
#define _rep(i,a,b) for(int i=(a);i<=(b);++i)
typedef long long LL;
const int INF = 0xffffff0;
const int MOD = 1e9 + 7;
const int maxn = 10005;
int n,ans;
void quicksort(int * a,int L,int R){
    if(L>=R)return;
    int key=a[L],pk=L,p2=R;
    while(pk!=p2){
        while(pk<p2&&key<=a[p2])p2--;
        swap(a[pk],a[p2]);
        while(pk<p2&&key>=a[pk])pk++;
        swap(a[pk],a[p2]);
    }
    if(pk==n/2){
        ans=a[pk];
        return;
    }
 
    quicksort(a,0,p2);
    quicksort(a,p2+1,R);
}
 
int main() {
	//freopen("C:\\Users\\admin\\Desktop\\in.txt", "r", stdin);
	//freopen("C:\\Users\\admin\\Desktop\\out.txt", "w", stdout);
    int a[maxn];
    scanf("%d",&n);
    _for(i,0,n)scanf("%d",&a[i]);
    //quicksort(a,0,n-1);
    //printf("%d\n",ans);
    sort(a,a+n);
    printf("%d\n",a[n/2]);
 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/tomandjake_/article/details/81542326