最小堆也调试通过

This commit is contained in:
建峰 2024-07-04 15:49:17 +08:00
parent 90d8cd340b
commit 0a97fc74b4
2 changed files with 70 additions and 25 deletions

View File

@ -57,6 +57,8 @@ static void heap_fixed_up(struct _heap* self, int i)
{ {
assert(self != NULL); assert(self != NULL);
int p = 0; int p = 0;
if(self->_min_flag != true)
{
while(1) while(1)
{ {
p = parent(i); p = parent(i);
@ -69,6 +71,21 @@ static void heap_fixed_up(struct _heap* self, int i)
i = p; i = p;
} }
} }
else
{
while(1)
{
p = parent(i);
// 若当前节点大于其父节点,则交换位置,否则退出循环
if(p < 0 || self->compare(self->obj + i * self->_obj_size, self->obj + p * self->_obj_size) >= 0)
{
break;
}
heap_swap(self, i, p);
i = p;
}
}
}
bool heap_push(struct _heap* self, void* obj) bool heap_push(struct _heap* self, void* obj)
{ {
@ -88,8 +105,10 @@ static void heap_fixed_down(struct _heap* self, int i)
{ {
assert(self != NULL); assert(self != NULL);
int l = 0,r = 0; int l = 0,r = 0;
int max = 0; int max = 0, min = 0;
if(self->_min_flag != true)
{
while(1) while(1)
{ {
l = left(i); l = left(i);
@ -113,6 +132,32 @@ static void heap_fixed_down(struct _heap* self, int i)
i = max; i = max;
} }
} }
else
{
while(1)
{
l = left(i);
r = right(i);
min = i;
if(l < self->size(self) && self->compare(self->obj + l * self->_obj_size, self->obj + min * self->_obj_size) < 0)
{
min = l;
}
if(r < self->size(self) && self->compare(self->obj + r * self->_obj_size, self->obj + min * self->_obj_size) < 0)
{
min = r;
}
if(min == i)
{
break;
}
heap_swap(self, i, min);
i = min;
}
}
}
bool heap_pop(struct _heap* self, void* obj) bool heap_pop(struct _heap* self, void* obj)
{ {

View File

@ -27,7 +27,7 @@ void test_heap_num(void)
// default: maxheap // default: maxheap
// maxheap or minheap // maxheap or minheap
// heap->setmin(heap, true); heap->setmin(heap, true);
printf("\n\n----- test_heap_num -----\n"); printf("\n\n----- test_heap_num -----\n");
@ -44,7 +44,7 @@ void test_heap_num(void)
printf("\n"); printf("\n");
} }
printf("----- max -----\n"); printf("----- max/min -----\n");
heap->peek(heap, &temp); heap->peek(heap, &temp);
heap->print_obj(&temp); heap->print_obj(&temp);
printf("\n"); printf("\n");