List *List_merge_sort(List *list, List_compare cmp) { assert(list != NULL && "list can't be NULL"); assert(cmp != NULL && "cmp can't be NULL"); if(List_count(list) <= SUB_LIST_MIN_SIZE) { int rc = List_bubble_sort(list, cmp); assert(rc == 0 && "Bubble sort failed."); return list; } List *left = List_create(); List *right = List_create(); int middle = List_count(list) / 2; List_split(list, left, middle, right, List_count(list) - middle); List *sort_left = List_merge_sort(left, cmp); List *sort_right = List_merge_sort(right, cmp); if(sort_left != left) List_clear_destroy(left); if(sort_right != right) List_clear_destroy(right); List *merged_list = List_merge(sort_left, sort_right, cmp); List_clear_destroy(sort_left); List_clear_destroy(sort_right); return merged_list; }
char *test() { List *list = List_create(); List_push(list, 5); List_push(list, 4); List_push(list, 3); List_push(list, 2); List_push(list, 1); List_bubble_sort(list); return NULL; }
char *test_bubble_sort() { List *words = create_words(); // should work on a list that needs sorting int rc = List_bubble_sort(words, (List_compare)strcmp); mu_assert(rc == 0, "Bubble sort failed"); mu_assert(is_sorted(words), "Words are not sorted after bubble sort"); // should work on a list that already sorted rc = List_bubble_sort(words, (List_compare)strcmp); mu_assert(rc == 0, "Bubble sort of already sorted failed"); mu_assert(is_sorted(words), "Words should be sort if already bubble sorted"); // should work on empty list List_destroy(words); words = List_create(); rc = List_bubble_sort(words, (List_compare)strcmp); mu_assert(rc == 0, "Bubble sort failed on empty list"); mu_assert(is_sorted(words), "Words should be sorted if empty"); List_destroy(words); return NULL; }
int List_bubble_sort_test(List *list) { List_bubble_sort(list, (List_compare)sort_asc); assert(is_sorted_asc(list)); return 0; }