Change list sort to stack-based
This commit is contained in:
		
							parent
							
								
									01a62cfaf3
								
							
						
					
					
						commit
						ec76ed2d14
					
				@ -16,38 +16,39 @@ static inline void lnode_swap(lnode_t* s0, lnode_t* s1) {
 | 
			
		||||
    s1->type = t;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
static inline lnode_t* pivot(lnode_t *l, lnode_t *r) {
 | 
			
		||||
 | 
			
		||||
    lnode_t *c = l->prev;
 | 
			
		||||
 | 
			
		||||
    for (lnode_t* i = l; i != r; i = i->next) {
 | 
			
		||||
        if (lnode_compare(i, r) < 0) {
 | 
			
		||||
            c = (is_null(c)) ? l : c->next;
 | 
			
		||||
            lnode_swap(c, i);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    c = (is_null(c)) ? l : c->next;
 | 
			
		||||
    lnode_swap(c, r);
 | 
			
		||||
 | 
			
		||||
    return c;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
static void quick_sort(lnode_t* l, lnode_t* r) {
 | 
			
		||||
    lnode_t* p;
 | 
			
		||||
 | 
			
		||||
    if (!is_null(r) && l != r && l != r->next) {
 | 
			
		||||
        p = pivot(l, r);
 | 
			
		||||
 | 
			
		||||
        quick_sort(l, p->prev);
 | 
			
		||||
        quick_sort(p->next, r);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/*#####################################################################################################################*/
 | 
			
		||||
 | 
			
		||||
void list_sort(list_t* x) {
 | 
			
		||||
    return quick_sort(x->first, x->last);
 | 
			
		||||
    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);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		Loading…
	
		Reference in New Issue
	
	Block a user