classSolution1{ publicintpartition(int[] nums, int low, int high){ // select one pivot to sort the array partly // and return the position of pivot int pos = high; int pivot = nums[casualPos]; while (low < high) { while (low < high && nums[low] <= pivot) low++; while (low < high && nums[high] >= pivot) high--; swap(nums, low, high); } swap(nums, pos, high); return high; }
publicvoidquicksort(int[] nums, int start, int end){ if (start < end) { int pivot = partition(nums, start, end); System.out.println("pivot=" + pivot); Arrays.stream(nums).forEach(System.out::print); System.out.println(); quicksort(nums, start, pivot - 1); quicksort(nums, pivot + 1, end); } }
publicvoidswap(int[] nums, int i, int j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; }
publicstaticvoidmain(String[] args){ int[] nums = newint[] {5,7,1,6,4,8,3,2 }; Solution1 slt = new Solution1(); slt.quicksort(nums, 0, nums.length - 1); for (int i : nums) { System.out.println(i); } } }
publicintpartition2(int[] nums, int low, int high){ // select one pivot to sort the array partly // and return the position of pivot int pivot = nums[high]; while (low < high) { while (low < high && nums[low] <= pivot) low++; pivot = nums[high]; nums[high] = nums[low]; nums[low] = pivot; while (low < high && nums[high] >= pivot) high--; pivot = nums[low]; nums[low] = nums[high]; nums[high] = pivot; } return high; }
publicvoidquicksort(int[] nums, int start, int end){ if (start < end) { int pivot = partition2(nums, start, end); System.out.println("pivot=" + pivot); Arrays.stream(nums).forEach(System.out::print); System.out.println(); quicksort(nums, start, pivot - 1); quicksort(nums, pivot + 1, end); } }
publicintpartition2(int[] nums, int low, int high){ // select one pivot to sort the array partly // and return the position of pivot int pivot = nums[high]; while (low < high) { while (low < high && nums[low] <= pivot) low++; nums[high] = nums[low]; while (low < high && nums[high] >= pivot) high--; nums[low] = nums[high]; } nums[high] = pivot; return high; }
publicvoidquicksort(int[] nums, int start, int end){ if (start < end) { int pivot = partition2(nums, start, end); System.out.println("pivot=" + pivot); Arrays.stream(nums).forEach(System.out::print); System.out.println(); quicksort(nums, start, pivot - 1); quicksort(nums, pivot + 1, end); } }