Random random = new Random(); publicintpartition(int[] nums, int start, int end){ //用随机数寻找基数 int idx = random.nextInt(end - start) + start; exchange(nums, start, idx); //交换基数和首位元素的位置,基数不参与排序 int pivot = nums[start]; int left = start + 1; int right = end; while (left < right) { while (left < right && nums[left] <= pivot) { left++; } if (left != right) { exchange(nums, left, right); right--; } } if (left == right && nums[right] > pivot) { right--; } if (right != start) { exchange(nums, right, start); } //返回基数的位置 return right; }
publicvoidexchange(int[] nums, int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }
publicvoidquickSort(int[] nums, int start, int end){ if (start >= end) return; //排到n/2位置提前停止,返回索引n/2位置的数 if (end <= nums.length / 2) return; int middle = partition(nums, start, end); quickSort(nums, start, middle - 1); quickSort(nums, middle + 1, end); }
publicintcount(int[] nums, int n){ int m = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == n) { m++; } } return m; }
publicintrandomPick(int nums[]){ Random random = new Random(); while (true) { int candidate = nums[random.nextInt(nums.length)]; int n = count(nums, candidate); if (n > nums.length / 2) { return candidate; } } }