快速排序(java)
作者:
枫桥夜泊
,
2024-08-05 17:42:08
,
所有人可见
,
阅读 8
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
quicksort(a,0,n-1);
for(int i=0;i<n;i++)
System.out.printf("%d ",a[i]);
}
private static void quicksort(int[] a,int left,int right){
if(left>=right)
return;
int pivot = a[left+right+1>>1],i = left-1,j = right+1;
while(i<j)
{
do i++;
while(a[i]<pivot);
do j--;
while(a[j]>pivot);
if(i<j)
{
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
quicksort(a,left,i-1);
quicksort(a,i,right);
}
}