【问题标题】:Merge Sort using sentinels in C# produces weird outputs在 C# 中使用哨兵进行合并排序会产生奇怪的输出
【发布时间】:2022-01-09 11:13:31
【问题描述】:

我正在尝试使用 C# 中的哨兵来实现合并排序算法。

我要排序的数组:

int[] arr = { 9, 8, 7, 6, 5, 4 };

这是我的合并排序函数:

void MergeSort(int[] arr, int lowerIndex, int upperIndex)
        {
            if (upperIndex > lowerIndex)
            {
                int midIndex = (lowerIndex + upperIndex) / 2;
                MergeSort(arr, lowerIndex, midIndex);
                MergeSort(arr, midIndex + 1, upperIndex);
                Merge(arr, midIndex, lowerIndex, upperIndex);

            }
        }

这是我的合并功能:

 void Merge(int[] arr, int midIndex, int lowerIndex, int upperIndex)
        {
            int leftArrayLength = midIndex - lowerIndex + 1;
            int rightArrayLength = upperIndex - midIndex;

            int[] left = new int[leftArrayLength + 1];
            int[] right = new int[rightArrayLength + 1];

            for (int i = 0; i < leftArrayLength; i++)
            {
                left[i] = arr[i];
            }
            for (int j = 0; j < rightArrayLength; j++)
            {
                left[j] = arr[midIndex + j];
            }

            //Sentinels
            left[leftArrayLength] = int.MaxValue;
            right[rightArrayLength] = int.MaxValue;

            int m = 0;
            int n = 0;
            for (int k = lowerIndex; k <= upperIndex; k++)
            {
                if (left[m] <= right[n])
                {
                    arr[k] = left[m];
                    m += 1;
                }
                else
                {
                    arr[k] = right[n];
                    n += 1;
                }

            }
        }

它给出了一个奇怪的输出:

0 0 0 7 0 4

到目前为止,我已经按照 CLRS 中给出的伪代码反复检查了我的实现,但我没有发现我的实现有什么问题。

请告诉我我做错了什么。

【问题讨论】:

  • 你在这里检查了吗? en.wikipedia.org/wiki/Merge_sort
  • @StefanW。是的,在将其发布到此处之前,我实际上确实经历了这一点,但我无法从中找到太多帮助。

标签: c# sorting mergesort


【解决方案1】:

left/right 数组初始化中至少有以下几个错误:

  • 对于left,你应该从lowerIndex开始:
for (int i = 0; i < leftArrayLength; i++)
{
    left[i] = arr[lowerIndex + i];
}
  • right 有两个错误 - 1) 数组名称拼写错误并使用 left 2) 索引出现“逐一错误”
for (int j = 0; j < rightArrayLength; j++)
{
   right[j] = arr[midIndex + 1 + j];
} 

【讨论】:

  • 相信我,我至少检查了 50 次代码,但仍然找不到这些新手错误。非常感谢您指出错误。现在它完美地工作了。
  • @Aniruddh 很乐意提供帮助!它发生在我们所有人身上——在过于熟悉的代码中跳过有时对新鲜人来说很明显的错误。因此,我建议您在这种情况下调试/单步调试您的代码 - 这是一种有用的技能,有时有助于发现此类错误。
猜你喜欢
  • 2020-05-14
  • 2012-02-29
  • 2017-08-16
  • 2021-03-08
  • 2013-04-06
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 2015-08-18
相关资源
最近更新 更多