#include #include #include struct Stuff { char text[11]; int order; }; static void swap_stuff(void *a_, void *b_) { struct Stuff *a = a_; struct Stuff *b = b_; struct Stuff tmp; tmp = *a; *a = *b; *b = tmp; } static int cmp_stuff(const void *a_, const void *b_, void *cookie) { const struct Stuff *a = a_; const struct Stuff *b = b_; (void)cookie; if (a->order < b->order) return -1; return 1; } void print_stuff(const struct Stuff *s, size_t len) { size_t i; for(i = 0; i < len; i++) { printf("%s:%d\n", s[i].text, s[i].order); } } static int cmp_stuff_array(const struct Stuff *a, const struct Stuff *b, size_t len) { size_t i; for (i = 0; i < len; i++) { if (strcmp(a[i].text, b[i].text) != 0) return -1; if (a[i].order != b[i].order) return -1; } return 0; } START_TEST (test_heapsort_odd) struct Stuff unordered[] = { {"2", 2}, {"1", 1}, {"4", 4}, {"5", 5}, {"3", 3}, }; struct Stuff ordered[] = { {"1", 1}, {"2", 2}, {"3", 3}, {"4", 4}, {"5", 5}, }; uc_heapsort(unordered, ARRAY_SIZE(unordered), sizeof(struct Stuff), cmp_stuff, swap_stuff, NULL); print_stuff(unordered, ARRAY_SIZE(unordered)); fail_if(cmp_stuff_array(unordered, ordered, ARRAY_SIZE(unordered)) != 0); END_TEST START_TEST (test_heapsort_even) struct Stuff unordered[] = { {"1", 1}, {"7", 7}, {"3", 3}, {"4", 4}, {"6", 6}, {"2", 2}, }; const struct Stuff ordered[] = { {"1", 1}, {"2", 2}, {"3", 3}, {"4", 4}, {"6", 6}, {"7", 7}, }; uc_heapsort(unordered, ARRAY_SIZE(unordered), sizeof(struct Stuff), cmp_stuff, swap_stuff, NULL); fail_if(cmp_stuff_array(unordered, ordered, ARRAY_SIZE(unordered)) != 0); END_TEST START_TEST (test_heapsort_zero_one) struct Stuff unordered[] = { {"1", 1}, {"7", 7}, {"3", 3}, {"4", 4}, {"6", 6}, {"2", 2}, }; const 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(cmp_stuff_array(unordered, same, ARRAY_SIZE(unordered)) != 0); uc_heapsort(unordered, ARRAY_SIZE(unordered), 0, cmp_stuff, swap_stuff, NULL); fail_if(cmp_stuff_array(unordered, same, ARRAY_SIZE(unordered)) != 0); uc_heapsort(unordered, 1, sizeof(struct Stuff), cmp_stuff, swap_stuff, NULL); fail_if(cmp_stuff_array(unordered, same, ARRAY_SIZE(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_one); suite_add_tcase(s, tc); return s; }