排序算法(六)快速排序验证性实验

请创建一个一维整型数组用来存储待排序关键码,关键码从数组下标为1的位置开始存储,下标为0的位置不存储关键码。输入关键码的个数,以及各个关键码,采用快速排序的方法对关键码数组进行排序,输出每轮比较的过程。

输入描述:

各个命令以及相关数据的输入格式如下:
第一行输入关键码的个数n
第二行输入n个整型关键码

输出描述:

输出关键码比较过程,将需要移动的关键码输出,每轮一行,关键码之间以空格隔开,最后一个关键码后有空格,然后回车,不重复输出,最后将排好序的关键码输出,以空格隔开,最后回车。

输入样例:

10
2 5 9 8 7 4 3 10 16 13

输出样例:

3 9 4 8
13
2 3 4 5 7 8 9 10 13 16 
#include<bits/stdc++.h>
using namespace std;
int P(int r[],int first,int end);
void Q(int r[],int first,int end);
int main()
{
	int n;cin>>n;int r[n];
	for(int i=0;i<n;i++)
	{
		cin>>r[i];
	}
	
	
	Q(r,0,n-1);
	
		for(int i=0;i<n;i++){
		cout<<r[i]<<" ";
	}
} 
void Q(int r[],int first,int end)
{if(first<end){
	
	int pivot=P(r,first,end);
	
	Q(r,first,pivot-1);
	
	Q(r,pivot+1,end);

}
}
int P(int r[],int first,int end)
{
	int i=first;

	int j=end;
	int flag=0;
	while(i<j)
	{
		while(i<j&&r[i]<=r[j]){
			j--;
		}
			
			if(i<j){
				int temp;
			temp = r[i];cout<<r[j]<<" ";
            r[i] = r[j];
            r[j] = temp;
            i++;
            flag=1;
            
			}
			while(i<j&&r[i]<=r[j])i++;
			
			if(i<j){
				int temp;
			temp = r[i];cout<<r[i]<<" ";
            r[i] = r[j];
            r[j] = temp;
            j--;           
            
            flag=1;
			}
				
	}
	if(flag!=0){
		cout<<endl;	
	}
	
	return i;
}

猜你喜欢

转载自blog.csdn.net/wfy2695766757/article/details/84677553