藍橋杯 ADV-297 算法提高 快速排序

資源限制
時間限制:1.0s 內存限制:256.0MB
問題描述
  用遞歸來實現快速排序(quick sort)算法。快速排序算法的基本思路是:假設要對一個數組a進行排序,且a[0] = x。首先對數組中的元素進行調整,使x放在正確的位置上。同時,所有比x小的數都位於它的左邊,所有比x大的數都位於它的右邊。然後對於左、右兩段區域,遞歸地調用快速排序算法來進行排序。
  輸入格式:輸入只有一行,包括若干個整數(不超過10個),以0結尾。
  輸出格式:輸出只有一行,即排序以後的結果(不包括末尾的0)。
輸入輸出樣例
樣例輸入
5 2 6 1 7 3 4 0
樣例輸出
1 2 3 4 5 6 7

此處@大雪菜,用的y總的快速排序板子,抽時間儘快把這個板子背過

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
//ios::sync_with_stdio(false);
typedef long long LL;
using namespace std;
const int MAXN = 1e8;
void quick_sort(int q[], int l, int r){
    if (l >= r) return;

    int i = l - 1, j = r + 1, x = q[l + r >> 1];
    while (i < j){
        do i ++ ; while (q[i] < x);
        do j -- ; while (q[j] > x);
        if (i < j) swap(q[i], q[j]);
    }
    quick_sort(q, l, j), quick_sort(q, j + 1, r);
}
int n;
int main() {
	int a[11], i = 0;
	while(scanf("%d", &n) != EOF) {
		if(n == 0) {
			break;
		}
		a[i++] = n;
	}
	quick_sort(a, 0, i-1);
	for(int j = 0; j < i; j++) {
		cout << a[j] << " ";
	}
	return 0;
}

晚安晚安,洗漱睡覺,每天都加油!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章