8642 快速排序
时间限制:1000MS 代码长度限制:10KB
提交次数:2105 通过次数:1352
题型: 编程题 语言: G++;GCC
Description
用函数实现快速排序,并输出每次分区后排序的结果
输入格式
第一行:键盘输入待排序关键的个数n
第二行:输入n个待排序关键字,用空格分隔数据
输出格式
每行输出每趟排序的结果,数据之间用一个空格分隔
输入样例
10
5 4 8 0 9 3 2 6 7 1
输出样例
1 4 2 0 3 5 9 6 7 8
0 1 2 4 3 5 9 6 7 8
0 1 2 4 3 5 9 6 7 8
0 1 2 3 4 5 9 6 7 8
0 1 2 3 4 5 8 6 7 9
0 1 2 3 4 5 7 6 8 9
0 1 2 3 4 5 6 7 8 9
#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<iostream>
#include<vector>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
//检查函数
void check(int num[],int n) {
for (int i = 1; i <= n; i++)cout << num[i] << " ";
cout << endl;
}
int quickSort(int num[], int low, int high) {
//先让low为基准点
int pivotkey = num[low];
//临时值
int tmp;
//循环结束条件是 low=high 该位置为基准点存放位置
while (low < high) {
//先从后往前找比基准点小的 相等的跳过 并且low要保证小于high
while (num[high] >= pivotkey&&low<high) {
high--;
}
//找到后交换
{
tmp = num[high]; num[high] = num[low]; num[low] = tmp;
}
//然后从前往后找比基准点大的
while (num[low] <= pivotkey&&low<high) {
low++;
}
//交换
{
tmp = num[high]; num[high] = num[low]; num[low] = tmp;
}
}
//最后返回的low=high 即为基准点存放的位置
num[low]=pivotkey;
return low;
}
//递归快排
void Sort(int num[], int low, int high,int n) {
//基准点
int pivotkey;
//如果low<high 即low high仍存在距离 继续递归下去
if (low < high) {
//排序好 基准点两边后 再次以该基准点为边界进行递归
pivotkey = quickSort(num, low, high);
//检查
check(num,n);
//左半部分递归
Sort(num, low, pivotkey - 1, n);
//右半部分递归
Sort(num, pivotkey + 1, high, n);
}
}
int main(void) {
ios::sync_with_stdio(0), cin.tie(0);
int n;
cin >> n;
int* num = new int[n + 1];
for (int i = 1; i <= n; i++) cin >> num[i];
Sort(num, 1, n, n);
return 0;
}