#include #include int List_bubble_sort(List *list, List_compare cmp) { List_validate(list); if(List_count(list) <= 1) { return 0; } int swapped = 1; while(swapped == 1) { swapped = 0; LIST_FOREACH(list, first, next, cur) { if(cur->next == NULL) { continue; } if(cmp(cur->value, cur->next->value) > 0) { List_swap(cur, cur->next); swapped = 1; } } } return 0; } List *List_merge(List *left, List *right, List_compare cmp) { List *result = List_create(); while(List_count(left) > 0 && List_count(right) > 0) { if(cmp(List_first(left), List_first(right)) <= 0) { List_push(result, List_shift(left)); continue; } List_push(result, List_shift(right)); } while(List_count(left) > 0) { List_push(result, List_shift(left)); } while(List_count(right) > 0) { List_push(result, List_shift(right)); } return result; } List *List_merge_sort(List *list, List_compare cmp) { if(List_count(list) <= 1) { return list;; } int i = 0; List *left = List_create(); List *right = List_create(); LIST_FOREACH(list, first, next, cur) { if(i % 2 == 0) { List_push(right, cur->value); } else { List_push(left, cur->value); } i++; } List *sort_left = List_merge_sort(left, cmp); List *sort_right = List_merge_sort(right, cmp); if(sort_left != left) { List_destroy(left); } if(sort_right != right) { List_destroy(right); } return List_merge(sort_left, sort_right, cmp); }