#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define N 20
#define MAX_VALUE 100 //生成随机数最大值
#define LINE_COUNT 10 //每行打印个数
template<class T>
int partition(T a[],int l,int r){
int i=l,j=r+1;
T x=a[l];
while(true){
while(a[++i]<x&&i<r);
while(a[--j]>x);
if(i>=j)
break;
swap(a[i],a[j]);
}
swap(a[l],a[j]);
return j;
}
template<class T>
void quickSort(T a[],int l,int r){
if(l<r){
int q=partition(a,l,r);
quickSort(a,l,q-1);
quickSort(a,q+1,r);
}
}
template<class T>
void printArray(T a[],int lineCount,int n){//lineCount为每行打印的个数
for(int i=0;i<n;i++){
cout<<a[i]<<"\t";
if(i%lineCount==(lineCount-1))
cout<<endl;
}
cout<<endl;
}
void main(){
srand((unsigned int)time(NULL));
int a[N];
for(int i=0;i<N;i++)
a[i]=rand()%MAX_VALUE+1;
cout<<"原数组"<<endl;
printArray(a,LINE_COUNT,N);
quickSort(a,0,N-1);
cout<<"排序后的数组"<<endl;
printArray(a,LINE_COUNT,N);
system("pause");
}
快速排序
最新推荐文章于 2023-12-01 23:14:38 发布