|
| 1 | +package problems.leetcode; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.Collections; |
| 5 | + |
| 6 | +public class QuickSort { |
| 7 | + |
| 8 | + // 5, 1, 4, 8, 0, 9 |
| 9 | + // pivot = 5 |
| 10 | + // 1, 4, 0, 5, 8, 9 |
| 11 | + |
| 12 | + private static void exch(int[] nums, int i, int j) { |
| 13 | + if (i == j) { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + int n = nums[i]; |
| 18 | + nums[i] = nums[j]; |
| 19 | + nums[j] = n; |
| 20 | + } |
| 21 | + |
| 22 | + private static int partition(int[] nums, int lo, int hi) { |
| 23 | + // Partition into nums[lo..i-1], a[i], nums[i+1..hi]. |
| 24 | + // where a[i] will be at its final place. |
| 25 | + int i = lo, j = hi + 1; // left and right scan indices |
| 26 | + int pivot = nums[i]; |
| 27 | + while (true) { |
| 28 | + // Scan right, scan left, check for scan complete, and exchange. |
| 29 | + while (nums[++i] < pivot) { |
| 30 | + if (i == hi) { |
| 31 | + break; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + while (pivot < nums[--j]) { |
| 36 | + if (j == lo) { |
| 37 | + break; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + if (i >= j) { |
| 42 | + break; |
| 43 | + } |
| 44 | + |
| 45 | + exch(nums, i, j); |
| 46 | + } |
| 47 | + |
| 48 | + exch(nums, lo, j); // put pivot = nums[j] into its final position |
| 49 | + return j; // with nums[lo..j-1] <= nums[j] <= nums[j+1..hi]. |
| 50 | + } |
| 51 | + |
| 52 | + private static void sort(int[] nums, int lo, int hi) { |
| 53 | + if (hi <= lo) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + int p = partition(nums, lo, hi); |
| 58 | + sort(nums, lo, p - 1); |
| 59 | + sort(nums, p + 1, hi); |
| 60 | + } |
| 61 | + |
| 62 | + // space: O(1) |
| 63 | + // runtime: |
| 64 | + // - O(NlgN) on avg, |
| 65 | + // - O(N^2) worst case, if the input is reverse sorted for e.g. |
| 66 | + // we can avoid worst-case by shuffling before sort. |
| 67 | + public static void sort(int[] nums) { |
| 68 | + if (nums == null || nums.length < 2) { |
| 69 | + return; |
| 70 | + } |
| 71 | + |
| 72 | + // shuffle the array to avoid the worst-case perf |
| 73 | + Collections.shuffle(Arrays.asList(nums)); |
| 74 | + sort(nums, 0, nums.length - 1); |
| 75 | + System.out.println(Arrays.toString(nums)); |
| 76 | + } |
| 77 | + |
| 78 | + public static void main(String[] args) { |
| 79 | + sort(new int[] { 1, 2, 3, 4, 5 }); |
| 80 | + sort(new int[] { 5, 4, 3, 2, 1 }); |
| 81 | + sort(new int[] { 1, 2, 3, 4, 5, 4, 3, 2, 1 }); |
| 82 | + } |
| 83 | + |
| 84 | +} |
0 commit comments