程序填空题:建立大根堆
堆是一种经过排序的完全二叉树,大根堆中父节点的值大于或等于子节点的值。下面将array数组中的元素,创建一个大根堆。其中,swap()是数值交换函数。
c++
#include <iostream>
using namespace std;
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void adjust_heap(int *Array, int index, int len)
{
int cur = index;
int right_child = 2 * (cur + 1);
while(right_child < len)
{
if(Array[right_child] < @@[Array[right_child-1]](4))
{
right_child--;
}
swap(Array[cur], Array[right_child]);
cur = right_child;
right_child =@@[ 2 * (cur + 1)](4);
}
if(right_child == len)
{
if(Array[len] >@@[ Array[right_child]](4))
{
swap(Array[right_child], Array[len]);
}
}
}
void make_heap(int *Array, int len)
{
int index = (len - 2)/2;
do{
adjust_heap(Array, index, len);
index--;
}while(index != -1);
}
int main()
{
const int len = 9;
int array[len] = {1,3,6,4,5,2,7,9,8};
make_heap(array, len);
for(int i = 0; i < len ; i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
return 0;
}
答案:
第1空:Array[right_child-1]
第2空: 2 * (cur + 1)
第3空: Array[right_child]
c++
#include <iostream>
using namespace std;
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void adjust_heap(int *Array, int index, int len)
{
int cur = index;
int right_child = 2 * (cur + 1);
while(right_child < len)
{
if(Array[right_child] < @@[Array[right_child-1]](4))
{
right_child--;
}
swap(Array[cur], Array[right_child]);
cur = right_child;
right_child =@@[ 2 * (cur + 1)](4);
}
if(right_child == len)
{
if(Array[len] >@@[ Array[right_child]](4))
{
swap(Array[right_child], Array[len]);
}
}
}
void make_heap(int *Array, int len)
{
int index = (len - 2)/2;
do{
adjust_heap(Array, index, len);
index--;
}while(index != -1);
}
int main()
{
const int len = 9;
int array[len] = {1,3,6,4,5,2,7,9,8};
make_heap(array, len);
for(int i = 0; i < len ; i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
return 0;
}
答案:
第1空:Array[right_child-1]
第2空: 2 * (cur + 1)
第3空: Array[right_child]