归并排序

这算法好久没看,都忘了。算法看上去简单,用代码实现一下。

void Merge(int r[], int r1[], int s, int m, int t) {
    int i = s;
    int j = m + 1;
    int k = s;
    while (i <= m && j <= t) {
        if (r[i] <= r[j]) {
            r1[k++] = r[i++];
        } else {
            r1[k++] = r[j++];
        }
    }
    
    while (i <= m) {
        r1[k++] = r[i++];
    }
    
    while (j <= m) {
        r1[k++] = r[j++];
    }
}

void MergeSort(int r[], int s, int t) {
    int m;
    int r1[400];
    if (s == t) {
        return;
    } else {
        m = (s + t) / 2;
        MergeSort(r, s, m);
        MergeSort(r, m+1, t);
        Merge(r, r1, s, m, t);
        for (int i = s; i <= t; i++) {
            r[i] = r1[i];
        }
    }
}

点赞