我正在尝试将一个最大堆堆成一个最小堆。出于某种原因,我没有得到我期望的结果。
我已经建立了我的最大堆,它的数组内容按预期显示:
60 50 30 20 40 10
当尝试 heapfy 上述数组并将其转换为最小堆时,所需的结果是:
10 20 30 60 50 40
但是,我得到的结果是:
10 20 60 50 40 30
这是我的功能:
struct _heap
{
int max; //array max
int pos; //current position
int* priority; //array gets initialized after.
};
typedef struct _heap heap_t;
void heapify_min(heap_t* h, int father)
{
int smallest = father;
int left = 2 * father + 1;
int right = 2 * father + 2;
if (left < h->pos && h->priority[left] < h->priority[smallest) {
smallest = left;
}
if (dir < h->pos && h->priority[right] < h->priority[smallest])
smallest = right;
if (smallest != father) {
swap(father,smallest,h->priority);
heapify_min(h,left);
}
}
void swap(int a, int b, int *v)
{
int f = v[a];
v[a] = v[b];
v[b] = f;
}
void build_heap(heap_t* h)
{
int n = h->pos;
int i2 = (n/2) -1;
int i;
for (i = i2;i>=0;i--) {
heapify_min(h,i);
}
}
任何见解都会非常有帮助。