【发布时间】: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。是的,在将其发布到此处之前,我实际上确实经历了这一点,但我无法从中找到太多帮助。