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 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class quickSort{ public static int[] sortArray(int[] nums) { shuffle(nums); sort(nums, 0, nums.length - 1); return nums; } public static void sort(int[] nums, int lo, int hi) { if (lo > hi) return; int p = partition(nums, lo, hi); sort(nums, lo, p-1); sort(nums, p+1, hi); } public static int partition(int[] nums, int lo, int hi) { int pivot = nums[lo]; int i = lo + 1, j = hi; while (i<=j) { while(i < hi && nums[i] <= pivot){ i++; } while(j > lo && nums[j] > pivot) { j--; } if(i>=j) { break; } swap(nums, i, j); } swap(nums, lo, j); return j; } public static void shuffle(int[] nums) { Random rand = new Random(); int n = nums.length; for(int i = 0; i<n; i++) { int r = i + rand.nextInt(n - i); swap(nums, i, r); } } public static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
|