Skip to content

ListSort

Description

Sort the list using a quicksort over a temporary contiguous buffer of the element values, then write the sorted order back into the list nodes.

Parameters

Name Direction Description
l in,out List to be sorted.
compare in Comparator returning a three-way ordering: negative when a < b, zero when equal, positive when a > b.

Success

Returns true. Elements are now in non-decreasing order according to compare. The list length and node count are unchanged; the scratch buffer has been released.

Failure

Returns false if the temporary contiguous buffer cannot be allocated. The list order and contents are unchanged.

Usage example (Cross-references)

Usage examples (Cross-references)
            // Advanced functions
            case LIST_INT_SORT : {
                ListSort(list, compare_ints);
                break;
            }
    
    static bool test_list_sort_and_reverse(void) {
        WriteFmt("Testing ListSort and ListReverse\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        ListPushBackR(&list, 2);
    
        ListSort(&list, compare_ints);
        bool result = list_matches(GENERIC_LIST(&list), (const int[]) {1, 2, 2, 3, 4}, 5);
    
    static bool test_list_sort_and_reverse_edge_cases(void) {
        WriteFmt("Testing ListSort and ListReverse edge cases\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        IntList singleton = ListInit(&alloc);
    
        ListSort(&empty, compare_ints);
        ListReverse(&empty);
        ListPushBackR(&singleton, 42);
        ListReverse(&empty);
        ListPushBackR(&singleton, 42);
        ListSort(&singleton, compare_ints);
        ListReverse(&singleton);
    
    static bool test_list_sort_without_compare_fails(void) {
        WriteFmt("Testing ListSort without compare function\n");
    
        List(int) list = ListInit(get_test_alloc());
        List(int) list = ListInit(get_test_alloc());
        ListPushBackR(&list, 10);
        ListSort(&list, NULL);
    
        return false;
    #define ListMustSort(l, compare)                                                                                       \
        do {                                                                                                               \
            if (!ListSort((l), (compare))) {                                                                               \
                LOG_FATAL("ListMustSort failed");                                                                          \
            }                                                                                                              \
Last updated on