Max Heap插入函数实现C++
我正在尝试将钥匙值插入堆中。我正在使用testunit.cpp出错。我得到了这些错误:
断言失败了。 预期:< [(10,100),(7,70),(6,60),(5,50),(2,20),(1,10),(1,10),(3,30),(4,40) ]> 实际:< [(7,70),(5,50),(6,60),(4,40),(2,20),(1,10),(1,10),(3,30),(10,100) ]>
断言失败了。 预期:< [(10,100),(4,40),(5,50),(1,10),(2,20),(3,30),(3,30)]> 实际:< [((5,50),(4,40),(3,30),(1,10),(2,20),(10,100),(10,100)]>
断言失败了。 预期:< [(9,90),(7,70),(8,80),(6,60),(2,20),(1,10),(1,10),(3,30),(5,5, 50)]> 实际:< [(9,90),(7,70),(8,80),(5,50),(2,20),(1,10),(1,10),(3,30),(6,6,, 60)]]>
断言失败了。 预期:< [(6,60),(5,50),(4,40),(1,10),(2,20),(3,30),(3,30)]> 实际:< [(6,60),(5,50),(3,30),(1,10),(2,20),(4,40)]>
我的插入功能是:
void insert(KeyValueType const& keyValue)
{
size_t asize = size();
if (asize == 0)
{
table.push_back(keyValue);
}
else
{
table.push_back(keyValue);
for (int i = asize / 2 - 1; i >= 0; i--)
{
heapify(i);
}
}
}
我的堆功能是:
void heapify(size_t index)
{
auto previous_index = index;
do
{
previous_index = index;
auto largest = getLargestFromParentAndHisChildren(index);
if (index != largest)
{
std::swap(table[index], table[largest]);
index = largest;
}
} while (index != previous_index);
}
I'm trying to insert key values into heap. I'm using TestUnit.cpp for errors. I got these errors:
Assert failed.
Expected:<[(10,100),(7,70),(6,60),(5,50),(2,20),(1,10),(3,30),(4,40)]>
Actual:<[(7,70),(5,50),(6,60),(4,40),(2,20),(1,10),(3,30),(10,100)]>
Assert failed.
Expected:<[(10,100),(4,40),(5,50),(1,10),(2,20),(3,30)]>
Actual:<[(5,50),(4,40),(3,30),(1,10),(2,20),(10,100)]>
Assert failed.
Expected:<[(9,90),(7,70),(8,80),(6,60),(2,20),(1,10),(3,30),(5,50)]>
Actual:<[(9,90),(7,70),(8,80),(5,50),(2,20),(1,10),(3,30),(6,60)]>
Assert failed.
Expected:<[(6,60),(5,50),(4,40),(1,10),(2,20),(3,30)]>
Actual:<[(6,60),(5,50),(3,30),(1,10),(2,20),(4,40)]>
My insert function is :
void insert(KeyValueType const& keyValue)
{
size_t asize = size();
if (asize == 0)
{
table.push_back(keyValue);
}
else
{
table.push_back(keyValue);
for (int i = asize / 2 - 1; i >= 0; i--)
{
heapify(i);
}
}
}
and my heapify function is :
void heapify(size_t index)
{
auto previous_index = index;
do
{
previous_index = index;
auto largest = getLargestFromParentAndHisChildren(index);
if (index != largest)
{
std::swap(table[index], table[largest]);
index = largest;
}
} while (index != previous_index);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的循环以错误的价值开始。它应该是:
不是您的问题,而是:
heapify
并不是最快的弹出价值的方法,因为该功能还需要检查同胞值,这是不必要的。i -
将使此循环o(n),这不是您想要的复杂性。此操作应为o(logn),因此,在每次迭代中,i
应该从子女跳到父母。Your loop starts at the wrong value. It should be:
Not your question, but:
heapify
is not the fastest way to bubble a value up, since that function needs to check also the sibling value, which is unnecessary.i--
will make this loop O(n), which is not the complexity you would want for a heap. This operation should be O(logn), and soi
should jump from child to parent, in each iteration.