提问人:Long.zhao 提问时间:11/15/2023 更新时间:11/15/2023 访问量:18
为什么快速选择这么慢?
Why quick select is so slow?
问:
public void findKthLargest(int[] nums, int k) {
// quick select for quickSelect1
quickSelect1(nums, 0, nums.length -1, nums.length - k);
// quick select for quickSelect2
quickSelect2(nums, 0, nums.length -1, k-1);
}
int quickSelect1(int[] nums, int l, int r, int k) {
if (l == r) return nums[k];
int x = nums[l], i = l - 1, j = r + 1;
while (i < j) {
do i++; while (nums[i] < x);
do j--; while (nums[j] > x);
if (i < j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
if (k <= j) return quickSelect1(nums, l, j, k);
else return quickSelect1(nums, j + 1, r, k);
}
private int quickSelect2(int[] nums, int left, int right, int k) {
if(left >= right)
return nums[k];
int p = new Random().nextInt(right - left + 1) + left;
int pp = nums[p];
swap(nums, p, left);
int i = left + 1;
int j = right;
while (true) {
while (i <= j && nums[i] >= pp) {
i++;
}
while (j >= i && nums[j] < pp) {
j--;
}
if(i > j)
break;
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
if(j != left)
swap(nums, j, left);
if(j == k)
return pp;
else if(j > k){
return quickSelect2(nums, left, j - 1, k);
}else{
return quickSelect2(nums, j + 1, right, k);
}
}
private void swap(int[] nums, int index1, int index2) {
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
那为什么这么慢呢?quickSelect2
quickSelect1
答: 暂无答案
上一个:我的快速排序方法未按预期工作
下一个:快速排序越界或循环
评论