Я реализовал задачи сортировки по выбору для класса, и одна из задач - найти 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-й наименьший элемент находиться в Любой справке, будет очень признателен!