前文:C++ 实现最大堆 及 最大堆排序
为寻找很多数中最小的k个数,使用堆
承接前文,在MaxHeap类中添加replaceTop方法,当新元素比堆顶小时,替换堆顶元素,并且重排堆保持堆特性,该replaceTop方法为:
void MaxHeap::replaceTop(int val)
{
if (val < a[0])
{
a[0] = val;
shiftDown(0);
}
}
验证程序为:
#include"MaxHeap.h"
#include<time.h>//为了产生随机数
int main()
{
srand((unsigned)time(NULL));
MaxHeap h(5);
int a[10];
for (int i = 0; i < 10; i++)
{
int temp = rand() % 100;
cout << temp << " ";
a[i] = temp;
}
for (int i = 0; i < 5; i++)
{
h.add(a[i]);
}
for (int i = 5; i < 10; i++)
{
h.replaceTop(a[i]);
}
h.sort();
system("pause");
return 0;
}
结果为: