You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归归并排序代码输出重复元素问题排查求助

Fixing Duplicate Elements in Your Recursive Merge Sort Code

I spot the issue immediately—your merge function has a critical mistake in the final copy step that's overwriting parts of your array with uninitialized values, leading to unexpected duplicates. Let's break down what's happening and how to fix it:

The Root Cause

In the merge function, after merging elements into the temporary array b, you're copying values back to the original array starting from index 0:

for (int i = 0; i <= h; i++)
    arr[i] = b[i];

But here's the problem: your temporary array b only contains valid merged values starting from index l (since you initialized k = l and filled b starting at that position). The elements from 0 to l-1 in b are uninitialized garbage. When you copy these into arr, you're overwriting the already sorted elements before l with random values, which often manifest as duplicates in your final output.

The Simple Fix

Adjust the copy loop to start at l instead of 0, so you only copy the segment of b that you actually populated:

for (int i = l; i <= h; i++)
    arr[i] = b[i];

Corrected Full Code

Here's the fixed version of your code, plus a note about a non-standard feature you might want to address for portability:

#include <iostream>
using namespace std;

void merge(int arr[], int l, int mid, int h) {
    int i = l;
    int j = mid + 1;
    int k = l;
    // Note: Variable-length arrays (VLAs) like int b[h+1] are not standard C++
    // For cross-compiler compatibility, use dynamic allocation or vector<int> instead
    int b[h + 1];
    while (i <= mid && j <= h) {
        if (arr[i] < arr[j])
            b[k++] = arr[i++];
        else
            b[k++] = arr[j++];
    }
    while (i <= mid)
        b[k++] = arr[i++];
    while (j <= h)
        b[k++] = arr[j++];
    // Corrected loop: only copy the valid merged segment
    for (int i = l; i <= h; i++)
        arr[i] = b[i];
}

void Rmerge_sort(int arr[], int l, int h) {
    if (l < h) {
        int mid = (h + l) / 2;
        Rmerge_sort(arr, l, mid);
        Rmerge_sort(arr, mid + 1, h);
        merge(arr, l, mid, h);
    }
}

int main() {
    int arr[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 10}, n = 10;
    Rmerge_sort(arr, 0, n - 1);
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}

Bonus: Standard C++ Improvement

The variable-length array int b[h+1] is a C99 feature that isn't part of standard C++. To make your code fully portable, replace it with a vector<int>:

#include <vector> // Add this include at the top

// Inside merge function:
vector<int> b(h + 1);

When you run the corrected code, it will output the properly sorted array without duplicates: 1 2 3 4 5 6 7 8 9 10.

内容的提问来源于stack exchange,提问作者Awasthi007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:02:27