大的放指标右边,小的放指标左边:交换左右指针
import java.util.Arrays; public class QuickSort { public static void main(String[] args) { int[] arr = new int[]{6, 1, 2, 7, 9, 3, 4, 5, 10, 8}; quickSort(arr,0,arr.length-1); System.out.println(Arrays.toString(arr)); } public static void quickSort(int[] arr,int left,int right){ if (left >= right){ return;//用于递归 } int base = arr[left]; int i = left; int j = right; while (i != j){ while (arr[j] >=base && i<j){ j--;//右指针大,就让右指针往左走 } while (arr[i] <= base && i<j){ i++;//左指针大,就让左指针往右走 } //如果左指针不大,右指针不小,就交换两个指针的位置 int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } arr[left] = arr[i]; arr[i] = base; quickSort(arr,left,i-1); quickSort(arr,i+1,right); } }