/* @description: Sorts the darray pointed to by p according to the comparison rules specified within the function pointed to by cmp. If the sort could not be completed, false is returned. Otherwise, true is returned. */ extern bool darray_sort(darray *p, int (*cmp)(const void*, const void*)) { size_t n = p->capacity; size_t i = n / 2; /* Make the entire array a valid heap */ while (i-- > 0) { if (!do_heap(p, i, n, cmp)) return false; } while (--n < (size_t)-1) { /* Place the maximum value and fix the heap for remaining elements */ if (!darray_swap(p, 0, n) || !do_heap(p, 0, n, cmp)) return false; } return true; }
/* @description: qsort-friendly implementation of heapsort for guaranteed time complexity. */ void _sort(void *base, size_t n, size_t size, _cmp_func_t cmp) { /* Not much can be done when size is unknown */ void *temp = _sys_alloc(size); uint8_t *p = (uint8_t*)base; int i = n / 2; /* Heapify the array */ while (i-- > 0) do_heap(p, i, n, size, cmp); /* Extrac the heap max and place it in sorted position */ while (--n < (size_t)-1) { /* Swap the heap max with base[n] */ memcpy(temp, p, size); memcpy(p, &p[n * size], size); memcpy(&p[n * size], temp, size); /* Re-heapify after removing the heap max */ do_heap(p, 0, n, size, cmp); } _sys_free(temp); }