题目
问题 C: DS排序--快速排序
时间限制: 1 Sec 内存限制: 128 MB
提交: 480 解决: 303
[提交][状态][讨论版]
题目描述
给出一个数据序列,使用快速排序算法进行从小到大的排序
--程序要求--
若使用C++只能include一个头文件iostream;若使用C语言只能include一个头文件stdio
程序中若include多过一个头文件,不看代码,作0分处理
不允许使用第三方对象或函数实现本题的要求
输入
第一行输入t,表示有t个测试示例
第二行输入n,表示第一个示例有n个数据
第三行输入n个数据,都是正整数,数据之间用空格隔开
以此类推
输出
每组测试数据,输出每趟快排的结果,即每次排好一个数字结果(长度为1的子序列,不用排,不用输出)。不同测试数据间用空行分隔。
样例输入
2
6
111 22 6 444 333 55
8
77 555 33 1 444 77 666 2222
样例输出
55 22 6 111 333 444
6 22 55 111 333 444
6 22 55 111 333 444
6 22 55 111 333 444
1 33 77 555 444 77 666 2222
1 33 77 555 444 77 666 2222
1 33 77 77 444 555 666 2222
1 33 77 77 444 555 666 2222
1 33 77 77 444 555 666 2222
代码块
#include <iostream>
using namespace std;
void Trace(int n, int *a)
{
int i;
for(i=0; i<n; i++)
{
if(i!=n-1)
cout<<a[i]<<' ';
else
cout<<a[i]<<endl;
}
}
int Partition(int first, int end, int *a)
{
int temp;
int i = first, j = end;
while(i<j)
{
while(i<j && a[i]<=a[j])
j--;
if(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
}
while(i<j && a[i]<=a[j])
i++;
if(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
j--;
}
}
return i;
}
void QuickSort(int first, int end, int n, int *a)
{
if(first<end)
{
int pos = Partition(first, end, a);
Trace(n, a);
QuickSort(first, pos-1, n, a);
QuickSort(pos+1, end, n, a);
}
}
int main(void)
{
int t;
cin>>t;
while(t--)
{
int i, n;
cin>>n;
int a[n];
for(i=0; i<n; i++)
cin>>a[i];
QuickSort(0, n-1, n, a);
cout<<endl;
}
}