⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 快速排序.cpp

📁 内有6个源程序代码,均为数据结构的实现代码
💻 CPP
字号:
#include<iostream.h>
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
static int counter=0;
static int counter0=0;
void swap(int *a,int *b){
    int c;
	if(*a>*b){
		c=*a;
	    *a=*b;
		*b=c;
	}
}
int partition(int a[],int p,int r){
	int i=p;
	int	j=r+1;
	int x=a[p];  
    while(1){
		do{
			if(i<=r)
			counter++;
		}while(a[++i]<x);
		do{
			if(j>=p)
			counter++;
		}while(a[--j]>x);			 
		if(i>=j)
			break;
		 swap(&a[i],&a[j]);
		 counter0++;
		}
	a[p]=a[j];
	a[j]=x;	 
	counter0++;
	return j;
}
void qSort(int a[],int p,int r){	 
 	if(p<r)
	{
	int q=partition(a,p,r); 
	qSort(a,p,q-1);
	qSort(a,q+1,r);
	}
}
 

void main(){ 
	int i,n;
	cout<<"输入比较个数:(不超过10000个)";
	cin>>n;
	if(n<=0||n>10000){
		cout<<"输入非法!";	 
		return;
	} 
	int a[10000];
	cout<<"比较前为:"<<endl;
	for(i=0;i<n;i++){
		a[i]=rand()%10000;
		cout<<a[i]<<' ';
	  	if(i%10==0) 	 	 
	 	cout<<endl; 
		}  
	cout<<endl;
    qSort(a,0,n-1);
	cout<<"比较后为:"<<endl;
 	for(int j=0;j<n;j++){
		cout<<a[j]<<' ';
		if(j%10==0)
			cout<<endl;	 
	} 
	cout<<endl;
	cout<<"比较次数为:";
	cout<<counter<<endl;
	cout<<"实际交换次数为:";
	cout<<counter0<<endl;
	cout<<"理论比较次数:";
	cout<<log(n)/log(2)*n<<endl;
	
}


	
	

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -