libcdsb/src/list/sort.c

66 lines
1.4 KiB
C

/* This software is licensed by the MIT License, see LICENSE file */
/* Copyright © 2022 Gregory Lirent */
#include "include.h"
/*#####################################################################################################################*/
static inline void lnode_swap(lnode_t* s0, lnode_t* s1) {
vnode_t v = s0->node;
vtype t = s0->type;
s0->node = s1->node;
s0->type = s1->type;
s1->node = v;
s1->type = t;
}
void list_sort(list_t* x) {
stack_t z = { .prev = 0, .value = x->last};
lnode_t *l;
lnode_t *r;
stack_push(&z, x->first);
while (z.value) {
l = stack_pop(&z);
r = stack_pop(&z);
if (!is_null(r) && l != r && l != r->next) {
lnode_t *p = l->prev;
for (lnode_t* c = l; c != r; c = c->next) {
if (lnode_compare(c, r) < 0) {
p = (is_null(p)) ? l : p->next;
lnode_swap(p, c);
}
}
p = (is_null(p)) ? l : p->next;
lnode_swap(p, r);
stack_push(&z, r);
stack_push(&z, p->next);
stack_push(&z, p->prev);
stack_push(&z, l);
}
}
}
void list_reverse(list_t* x) {
lnode_t *l = x->first;
lnode_t *r = x->last;
while (l != r) {
lnode_swap(l, r);
if ((r = r->prev) == l)
break;
l = l->next;
}
}