AcWing 785. 快速排序
原题链接
简单
作者:
SupEddie
,
2021-04-20 22:53:55
,
所有人可见
,
阅读 309
package com.xiaobai.sort;
import java.util.Scanner;
/**
* @author zhangsiyuan11445
* @date 2021/4/20
*/
public class QuickSort {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int n =scanner.nextInt();
int []arr =new int[n];
for(int i= 0;i<n;i++){
arr[i]=scanner.nextInt();
}
quickSort(arr,0,n-1);
for (int i =0;i<n;i++){
System.out.println(arr[i]+" ");
}
}
public static void quickSort(int []arr,int left,int right){
if(left>=right){
return;
}
// 为了能够比较区间端点的值
int i = left -1;
int j = right+1;
int x = arr[left+right>>1];
while (i<j){
do {i++;}while (arr[i]<x);
do {j--;}while (arr[j]>x);
if (i<j) {swap(arr,i,j);}
}
quickSort(arr,left,j);
quickSort(arr,j+1,right);
}
public static void swap(int []arr,int i, int j){
int tmp = arr[i];
arr[i]=arr[j];
arr[j] =tmp;
}
}