排序 - 归并排序(C语言)


时间复杂度:O(NlogN)

空间复杂度:O(N)

稳定性:稳定

// 归并排序
void merge_sort(int list[], int n) {
    /* perform a merge sort on the list. */
    int length = 1;
    int extra[100];

    while (length < n) {
        merge_pass(list, extra, n, length);
        length *= 2;
        merge_pass(extra, list, n, length);
        length *= 2;
    }
}


// 归并排序: 归并两个已排序的表,例如:int sorted_list[10] = { 2,3,5,6,9,1,4,10,12,14 },则 merge(sorted_list, sorted, 0, 4, 9);
void merge(int list[], int sorted[], int i, int m, int n) {
    /* merge two sorted lists: list[i], ..., list[m], and
    list[m+1], ..., list[n]. These lists are sorted to
    obtain a sorted list: sorted[i], ..., sorted[n] */
    int j, k, t;
    j = m + 1;
    k = i;
    while (i <= m && j <= n) {
        if (list[i] <= list[j])
            sorted[k++] = list[i++];
        else
            sorted[k++] = list[j++];
    }
    if (i > m)
        /* sorted[k], ... , sorted[n] = list[j], ..., list[n] */
        for (t = j; t <= n; t++)
            sorted[k + t - j] = list[t];
    else
        /* sorted[k], ... , sorted[n] = list[i], ..., list[m] */
        for (t = i; t <= m; t++)
            sorted[k + t - i] = list[t];
}


// 单次归并排序
void merge_pass(int list[], int sorted[], int n, int length) {
    /* perform one pass of the merge sort. It merges adjacent
    pairs of sub-lists from list into sorted. n is the 
    number of elements in the list. length is the length of the
    sub-list. */
    int i, j;
    for (i = 0; i <= n - 2 * length; i += 2 * length)
        merge(list, sorted, i, i + length - 1, i + 2 * length - 1);
    if (i + length < n)
        merge(list, sorted, i, i + length - 1, n - 1);
    else
        for (j = i; j < n; j++)
            sorted[j] = list[j];
}