快速排序_java实现

public class QuickSort {
	private static int []a;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n  = sc.nextInt();
		a = new int[n];
		for(int i = 0;i<a.length;i++){
			a[i] = sc.nextInt();
		}
		quicksort(0,n-1);
		
		for(Integer obj:a){
			System.out.println(obj);
		}
	}
	private static void swap(int i,int j){
		int temp = a[i];
		a[i] = a[j];
		a[j]=temp;
	}
	private static void quicksort(int left, int right) {
		if(left>=right){
			return;
		}
		int temp =a[left];//每一段数组中第一个元素是基准数
		int i = left;
		int j = right;
		while(i<j){
			while(a[j]>=temp&&i<j)
				j--;
			while(a[i]<=temp&&i<j)
				i++;
			if(i<j)
				swap(i,j);
		}
		
		//将基准元素放到合适位置
		swap(left,i);
		
		quicksort(left, i-1);
		quicksort(i+1, right);
		
	}
}
点赞