AcWing 785. 快速排序
原题链接
简单
作者:
Pluto_40
,
2020-05-29 14:22:46
,
所有人可见
,
阅读 2
Java代码
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] nums = new int[n];
for(int i = 0; i<n; i++){
nums[i]= s.nextInt();
}
quickSort(nums, 0, n-1);
for(int i = 0; i< n; i++){
System.out.print(nums[i] + " ");
}
}
public static void quickSort(int[] arr, int l , int r){
if(l >= r) return ;
swap(arr, l + (int)(Math.random()*(r-l+1)), r);
int[] p = partition(arr, l, r);
quickSort(arr, l, p[0]-1);
quickSort(arr, p[1]+1, r);
}
public static int[] partition(int[] nums, int l , int r){
int less = l - 1;
int more = r + 1;
int x = nums[r];
while(l < more){
if(nums[l] < x){
swap(nums, l++ ,++less);
}else if(nums[l] > x){
swap(nums, l, --more);
}else{
l++;
}
}
return new int[]{less + 1, more -1};
}
static void swap(int[] arr, int i, int j){
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}