简单讲,快速排序算法就是:给定一个含有n个数字的序列,先确定中轴值pivot,确定中轴值pivot位置,从而将一个数组分成两部分:左边数组下边范围[1,pivot],右边下标范围[pivot+1,n](下标从1开始)。左边的序列每个元素都比pivot小,右边每个序列都比pivot大。之后再分别对左右两边的子数组再进行如上操作。
例如,对于给定序列:
[6,8,9,4,2,7,5]
假定pivot为数组第一个元素6,先确定它的位置,之后将其分成两部分,即:
[5,2,4,6],[9,7,8]
再对左右两部分重复操作,左边中轴值为5,右边为9:
[4,2,5],[6],
[8,7,9]
重复,数组1中轴值4,数组2为单个元素无操作,数组3中轴值为8,数组4为空:
[2,4],[5],[6],
[7,8,9]
排序完成
题目与代码如下:
/*
题目描述:
对输入的n个数进行排序并输出。
输入:
输入的第一行包括一个整数n(1<=n<=100)。
接下来的一行包括n个整数。
输出:
可能有多组测试数据,对于每组数据,将排序后的n个整数输出,每个数后面都有一个空格。
每组测试数据的结果占一行。
样例输入:
4
1 4 3 2
样例输出:
1 2 3 4 */
#include<iostream>
using namespace std;
//确定中轴值pivot
int partition(int a[],int front,int back){
int pviot = a[front];
int temp;
while(front<back){
while(front<back && a[back]>pviot){
back--;
}
temp = a[back];
a[back] = a[front];
a[front] = temp;
while(front<back && a[front]<pviot){
front++;
}
temp = a[front];
a[front] = a[back];
a[back] = temp;
}
return front;
}
//排序过程用到递归
void quickSort(int x[],int front,int back){
if(front < back){
int pivot;
pivot = partition(x,front,back);//获得中轴值
quickSort(x,front,pivot);//对前半数列x[1,pivot]排序
quickSort(x,pivot+1,back);//对后半数列x[pivot+1,n]排序
}
}
//输入数据、调用函数以及打印结果
int main(){
int n;
int x[100];
cin>>n;
for(int i=1;i<=n;i++){//x[0]留下做temp
cin>>x[i];
}
quickSort(x,1,n);
for(int i=1;i<=n;i++){
cout<<x[i]<<" ";
}
}