voidsort(ElemType* base, size_t n, int (*ptrCompFunc)(const ElemType* x, const ElemType* y)); /* base: 指向排序数组的首个元素 n: 待排序数组的大小 ptrCompFunc: 排序用的比较函数 */
具体实现
冒泡排序
Time complexity: T(N)=O(N2)
Space complexity: T(N)=O(1)
voidbubbleSort(ElemType* base, size_t n, int (*ptrCompFunc)(const ElemType* x, const ElemType* y)){ for(size_t i = 0; i < n - 1; ++i) for(size_t j = i; j < n; ++j) if(!(*ptrCompFunc)(base + i, base + j)) swap(base + i, base + j); }
插入排序
Time complexity: T(N)=O(N2)
Space complexity: T(N)=O(1)
voidinsertionSort(ElemType* base, size_t n, int (*ptrCompFunc)(const ElemType* x, const ElemType* y)){ for(size_t i = 1; i < n; ++i){ size_t tmp = i; size_t j; for (j = i; j > 0 && (*ptrCompFunc)(base + tmp, base + j - 1); --j) base[j] = base[j - 1]; base[j] = base[tmp]; } }
选择排序
Time complexity: T(N)=O(N2)
Space complexity: T(N)=O(1)
voidselectionSort(ElemType* base, size_t n, int (*ptrCompFunc)(const ElemType* x, const ElemType* y)){ for(size_t i = 0; i < n - 1; ++i){ size_t m = i; for(size_t j = i + 1; j < n; ++j){ if((*ptrCompFunc)(base + j, base + m)){ m = j; } } swap(base + i, base + m); } }