资源限制
时间限制: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;
}
晚安晚安,洗漱睡觉,每天都加油!