50 lines
1.0 KiB
C
50 lines
1.0 KiB
C
/*
|
|
* Copyright (c) Camden Dixie O'Brien
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
*/
|
|
|
|
#include "min_heap.h"
|
|
#include "testing.h"
|
|
|
|
#include <stdbool.h>
|
|
|
|
static bool is_min_heap(int *xs, int count)
|
|
{
|
|
for (int i = 0; i < count; ++i) {
|
|
const int left = 2 * i + 1;
|
|
const int right = 2 * i + 2;
|
|
if (left < count && xs[left] < xs[i])
|
|
return false;
|
|
if (right < count && xs[right] < xs[i])
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static void array_is_min_heap_after_heapify(void)
|
|
{
|
|
int xs[] = { 54, 12, 35, 43, 21, 12, 34, 52, 34, 23 };
|
|
const int len = sizeof(xs) / sizeof(int);
|
|
min_heap_heapify(xs, len);
|
|
ASSERT_TRUE(is_min_heap(xs, len));
|
|
}
|
|
|
|
static void extract_root_yields_min(void)
|
|
{
|
|
int xs[] = { 71, 31, 12, 21, 65, 53, 54, 10 };
|
|
int len = 8;
|
|
min_heap_heapify(xs, len);
|
|
ASSERT_EQ(10, min_heap_pop(xs, &len));
|
|
ASSERT_EQ(12, min_heap_pop(xs, &len));
|
|
ASSERT_EQ(21, min_heap_pop(xs, &len));
|
|
ASSERT_EQ(5, len);
|
|
}
|
|
|
|
int main(void)
|
|
{
|
|
TESTING_BEGIN();
|
|
array_is_min_heap_after_heapify();
|
|
extract_root_yields_min();
|
|
return TESTING_END();
|
|
}
|