快排的核心在于:每次找到一个基准值的下标,并分别对基准值的两边进行快排。
动图:
代码:
public class QuickSort {
public static void main(String[] args){
int[] nums = new int[]{ 8, 9, 1, 7, 2, 3, 5, 4, 6, 0 };
int[] res = sort(nums, 0, nums.length-1);
for(int i=0; i<res.length; i++){
System.out.print(res[i] + " ");
}
}
public static int[] sort(int[] nums, int left, int right){ // 快排核心
if(left >= right){
return nums;
}
int middle = partition(nums, left, right);
// 每次找到基值下标,都对两边分别进行快排
sort(nums, left, middle - 1);
sort(nums, middle + 1, right);
return nums;
}
public static int partition(int[] nums, int left, int right){ // 计算基值存放下标
int i = left;
int j = right;
int povit = nums[left]; // 选定最左边的值作为基值(被比较的值)
while (i < j){
while ((i < j) && (nums[j] >= povit)){
j--;
}
while ((i < j) && (nums[i] <= povit)){
i++;
}
/*
不满足上面的条件时,说明左边的数大于等于右边的数,
此时需要进行交换,保证基值右边的数要比左边的大
*/
swap(nums, i, j);
}
swap(nums, left, i); // 找到基值下标,将原先选定的基值放在该下标表示的位置
return i;
}
private static void swap(int[] array, int a, int b){
int temp = array[a];
array[a] = array[b];
array[b] = temp;
}
}