box-o-sand/lcthw-remnants-2/liblcthw/src/lcthw/list_algos.c

80 lines
1.4 KiB
C
Raw Normal View History

#include <lcthw/list_algos.h>
int List_bubble_sort(List *list, List_compare cmp)
{
List_validate(list);
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_sort_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_copy(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++;
}
left = List_merge_sort(left, cmp);
right = List_merge_sort(right, cmp);
List *result = _List_merge_sort_merge(left, right, cmp);
List_destroy(left);
List_destroy(right);
return result;
}