diff --git a/src/heapsort.c b/src/heapsort.c index 1157da5..45a56e5 100644 --- a/src/heapsort.c +++ b/src/heapsort.c @@ -29,9 +29,17 @@ void uc_heapsort(void *base_, size_t count, size_t width, uc_hs_cmp cmp, uc_hs_swp swap, void *cookie) { - int start = count / 2 - 1, end = count - 1; + long start; + long end; unsigned char *base = base_; + if (count == 0 || width == 0) { + return; + } + + start = count / 2 - 1, + end = count - 1; + while (start >= 0) { uc_sift(base, start, count, width, cmp, swap, cookie); start--; diff --git a/test/test_heapsort.c b/test/test_heapsort.c index 520c6aa..3e84463 100644 --- a/test/test_heapsort.c +++ b/test/test_heapsort.c @@ -81,16 +81,44 @@ START_TEST (test_heapsort_even) uc_heapsort(unordered, ARRAY_SIZE(unordered), sizeof(struct Stuff), cmp_stuff, swap_stuff, NULL); - print_stuff(unordered, ARRAY_SIZE(unordered)); fail_if(memcmp(unordered, ordered, sizeof unordered) != 0); END_TEST +START_TEST (test_heapsort_zero) + struct Stuff unordered[] = { + {"1", 1}, + {"7", 7}, + {"3", 3}, + {"4", 4}, + {"6", 6}, + {"2", 2}, + }; + + struct Stuff same[] = { + {"1", 1}, + {"7", 7}, + {"3", 3}, + {"4", 4}, + {"6", 6}, + {"2", 2}, + }; + + uc_heapsort(unordered, 0, sizeof(struct Stuff), + cmp_stuff, swap_stuff, NULL); + fail_if(memcmp(unordered, same, sizeof unordered) != 0); + + uc_heapsort(unordered, ARRAY_SIZE(unordered), 0, + cmp_stuff, swap_stuff, NULL); + fail_if(memcmp(unordered, same, sizeof unordered) != 0); +END_TEST + Suite *heapsort_suite(void) { Suite *s = suite_create("heapsort"); TCase *tc = tcase_create("heapsort tests"); tcase_add_test(tc, test_heapsort_odd); tcase_add_test(tc, test_heapsort_even); + tcase_add_test(tc, test_heapsort_zero); suite_add_tcase(s, tc);