1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public class QuickSort { public void sort(int[] nums) { if (nums == null || nums.length == 0) { return; } quickSort(nums, 0, nums.length - 1); }
private void quickSort(int[] nums, int left, int right) { if (left >= right) { return; } int pivot = partition(nums, left, right); quickSort(nums, left, pivot - 1); quickSort(nums, pivot + 1, right); }
private int partition(int[] nums, int left, int right) { int pivot = nums[left]; int i = left + 1; int j = right; while (i <= j) { if (nums[i] < pivot && nums[j] > pivot) { swap(nums, i, j); i++; j--; } else if (nums[i] >= pivot) { i++; } else if (nums[j] <= pivot) { j--; } } swap(nums, left, j); return j; }
private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
|