Merge sort in C++

/*
 * A is an array and p, q, and r are indices numbering elements of the array
 * such that p <= q < r.
 *
 * This procedure assumes that the subarrays A[p. .q] and A[q + 1. .r] are in
 * sorted order. It merges them to form a single sorted subarray that replaces
 * the current subarray A[p. .r].
 */
void merge(int A[], int p, int q, int r) {
    int i, j, k, size;
    int* B;
   
    size = r - p + 1;

    B = new int[size]; /* temp arry for storing the merge result */
   
    /* initialize B */
    for (i = 0; i < size; ++i) {
        B[i] = 0;
    }

    i = p;
    j = q + 1;
    k = 0;
   
    /* compare and copy the smaller to B */
    while (i <= q && j <= r) {
        if (A[i] < A[j]) {
            B[k++] = A[i++];
        } else {
            B[k++] = A[j++];
        }
    }
   
    /* copy the rest to B */
    while (i <= q) {
        B[k++] = A[i++];
    }   
    while (j <= r) {
        B[k++] = A[j++];
    }
   
    /* replace A[p..r] with B[0..r-p] */
    for (i = p, k = 0; i <= r; ++i, ++k) {
        A[i] = B[k];
    }

    delete[] B;
}

/*
 * This procedure sorts the elements in the subarray A[p. .r].
 *
 * If p >= r, the subarray has at most one element and is therefore
 * already sorted. Otherwise, the divide step simply computes an index
 * q that partitions A[p. .r] into two subarrays: A[p. .q], containing n/2
 * elements, and A[q + 1. .r], containing n/2 elements.
 */
void mergeSort(int A[], int p, int r) {
    if (p >= r) return;
   
    int q = (p + r) / 2;
   
    mergeSort(A, p, q);
    mergeSort(A, q + 1, r);
    merge(A, p, q, r);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值