我一直在为班级实现选择排序问题,其中一个任务是使用最小堆在数组中查找第k个最小元素。我知道这个过程是:
- 堆化数组
- 删除最小值(根)k次
- 返回组中第k个最小元素
我没有任何问题创建最小堆。我只是不确定如何正确地删除最小值k次,并成功返回组中第k个最小元素。以下是我目前的进展:
bool Example::min_heap_select(long k, long & kth_smallest) const {
//duplicate test group (thanks, const!)
Example test = Example(*this);
//variable delcaration and initlization
int n = test._total ;
int i;
//Heapifying stage (THIS WORKS CORRECTLY)
for (i = n/2; i >= 0; i--) {
//allows for heap construction
test.percolate_down_protected(i, n);
}//for
//Delete min phase (THIS DOESN'T WORK)
for(i = n-1; i >= (n-k+1); i--) {
//deletes the min by swapping elements
int tmp = test._group[0];
test._group[0] = test._group[i];
test._group[i] = tmp;
//resumes perc down
test.percolate_down_protected(0, i);
}//for
//IDK WHAT TO RETURN
kth_smallest = test._group[0];
void Example::percolate_down_protected(long i, long n) {
//variable declaration and initlization:
int currPos, child, r_child, tmp;
currPos = i;
tmp = _group[i];
child = left_child(i);
//set a sentinel and begin loop (no recursion allowed)
while (child < n) {
//calculates the right child's position
r_child = child + 1;
//we'll set the child to index of greater than right and left children
if ((r_child > n ) && (_group[r_child] >= _group[child])) {
child = r_child;
}
//find the correct spot
if (tmp <= _group [child]) {
break;
}
//make sure the smaller child is beneath the parent
_group[currPos] = _group[child];
//shift the tree down
currPos = child;
child = left_child(currPos);
}
//put tmp where it belongs
_group[currPos] = tmp;
}
正如我之前所述,最小堆部分工作正常。我知道该做什么——删除根k次似乎很容易,但是在此之后,我应该返回数组中的哪个索引……0吗?这几乎可以解决问题——但它不能处理k = n或k = 1.第k小的元素是否会在任何地方出现?非常感谢您的任何帮助!
nth_element
部分排序给定的数组,这可能比基于堆的方法更快。 - Potatoswatter