[习题35]快速排序

2019-01-14  本文已影响12人  AkuRinbu

使用教材

《“笨办法” 学C语言(Learn C The Hard Way)》
https://www.jianshu.com/p/b0631208a794

https://github.com/zedshaw/liblcthw

标准C库中的排序函数

void qsort( void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *) );
ptr - 指向待排序的数组的指针
count - 数组的元素数目
size - 数组每个元素的字节大小
comp - 比较函数。若首个参数小于第二个,则返回负整数值,若首个参数大于第二个,则返回正整数值,若两参数相等,则返回零。
https://en.cppreference.com/w/c/algorithm/qsort

部分源码

typedef int (*DArray_compare) (const void *a, const void *b);

int DArray_qsort(DArray * array, DArray_compare cmp);
#include <lcthw/darray_algos.h>
#include <stdlib.h>

int DArray_qsort(DArray * array, DArray_compare cmp)
{
    qsort(array->contents, DArray_count(array), sizeof(void *), cmp);
    return 0;
}
#include <lcthw/darray_algos.h>

int testcmp(char **a, char **b)
{
    return strcmp(*a, *b);
}

char *run_sort_test(int (*func)(DArray *, DArray_compare), const char *name)
{
    DArray *words = create_words();
    mu_assert(!is_sorted(words), "words should start not sorted.");

    debug("---- Testing %s sorting algorithm", name);
    int rc = func(words, (DArray_compare)testcmp);
    mu_assert(rc == 0, "sort failed");
    mu_assert(is_sorted(words), "didn't sort it");

    DArray_destroy(words);

    return NULL;
}

char *test_qsort()
{
    return run_sort_test(DArray_qsort, "qsort");
}

复习回顾

https://www.jianshu.com/p/a63b9575c86a

https://www.jianshu.com/p/41379374bae7

上一篇 下一篇

猜你喜欢

热点阅读