快速排序练习
步骤: (1) 选择基准值。 (2) 将数组分成两个子数组:小于基准值的元素和大于基准值的元素。 (3) 对这两个子数组进行快速排序。 //对一个数组进行排序 public class QuickSort { //快速排序 private static void quickSort(int[] arr, int low, int high) { if (low > high) { return; } //基准值 int temp = arr[low]; int i = low; int j = high; while (i < j) { //j从尾部向前遍历找到比temp小的数就停止 while (arr[j] >= temp && i < j) { j--; } //i从起始向后遍历找到比temp大的数就停下 while (arr[i] <= temp && i < j) { i++; } //此时j所在的位置小于基准值,i所在的位置大于基准值 交换彼此 if (i < j) { int tempSwap = arr[j]; arr[j] = arr[i]; arr[i] = tempSwap; } } //i = j ,交换彼此 arr[low] = arr[i]; arr[i] = temp; //遍历基准值左边的数组 quickSort(arr, low, j - 1);