快速排序
作者:
高歌猛进
,
2024-08-03 23:08:37
,
所有人可见
,
阅读 2
#include<stdio.h>
int partition(int a[],int low,int high){
int k = a[low]; //将序列最左边的设为基准值,赋值给k
while(low < high){
while(low<high && a[high] >= k) high--; //从右往左找小于k的值
a[low] = a[high]; //将a[high]移到a[low]的位置
while(low<high && a[low]<=k) low++; //从左往右找大于k的值
a[high] = a[low]; //将a[low]移到a[high]的位置
}
a[low] = k;//最后low=high,将基准值赋值给low
return low;//返回基准值的下标,进行下一次递归
}
void quickSort(int a[],int low,int high){
if(low<high){
int p = partition(a,low,high); //找基准值
quickSort(a,low,p-1); //快排左序列
quickSort(a,p+1,high); //快排右序列
}
}
int main(){
int n;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++) scanf("%d",&a[i]);
quickSort(a,0,n-1);
for(int i=0;i<n;i++) printf("%d ",a[i]);
}