HDU 1425 sort 快速排序

sort

Time Limit: 6000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 46140 Accepted Submission(s): 13318

Problem Description
給你n個整數,請按從大到小的順序輸出其中前m大的數。

Input
每組測試數據有兩行,第一行有兩個數n,m(0 < n,m < 1000000),第二行包含n個各不相同,且都處於區間[-500000,500000]的整數。

Output
對每組測試數據按從大到小的順序輸出前m大的數。

Sample Input
5 3
3 -35 92 213 -644

Sample Output
213 92 3

Hint
請用VC/VC++提交

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1425

就是普通的快排,快排詳解博客鏈接:

http://blog.csdn.net/morewindows/article/details/6684558


#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <stack>
#include <queue>
#include <vector>
#define INF 0xffffffff
using namespace std;

const int maxn = 1000000+6;
int s[maxn];

void quick_sort(int l, int r, int m){
    if(l < r){
        int i=l, j=r, x=s[l];   //選第一個值爲基準數 
        while(i < j){
            while(i<j && s[j]<x) j--;
            if(i<j) s[i++] = s[j];      //從右往左找到第一個比基準數大的,填入位置i 
            while(i<j && s[i]>=x) i++;
            if(i<j) s[j--] = s[i];      //從左往右找到第一個比基準數小的,填入位置j 
        }
        s[i] = x;               //i==j,填入基準數 
        quick_sort(l, i-1, m);
        if(i<=m)               //只要排序前m個就夠了
            quick_sort(i+1, r, m);
    }
}

int main(){
    int n, m;
    while(scanf("%d%d", &n ,&m) == 2 && n){
        for(int i=0; i<n ;i++){
            scanf("%d", &s[i]); 
        }   
        quick_sort(0, n-1, m);
        for(int i=0; i<m; i++){
            if(i == 0){
                printf("%d", s[i]);
                continue;
            }
            printf(" %d", s[i]);
        }
        printf("\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章