gpt4 book ai didi

c# - C# 中的简单归并排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:29:57 25 4
gpt4 key购买 nike

我一直在对排序算法进行小幅修改,并遇到了合并排序。我已经编写了我的代码,并且在最后一个小时里一直在修改它,以确定它为什么仍然不能工作。我收到标准的 StackOverFlow 异常。谁能告诉我算法有什么问题?提前致谢。到目前为止我写的是:

public Int32[] MergeSort(Int32[] array)
{
int counter = 0;
if (array.Length == 0) { return array; }
int mid = array.Length / 2;
Int32[] leftHalf = new Int32[mid+1];
Int32[] rightHalf = new Int32[mid+1];
for (int i = 0; i < mid; i++) {
leftHalf[i] = array[i];
}
for (int j = mid; j < array.Length; j++) {
rightHalf[counter] = array[j];
counter++;
}
counter = 0;
MergeSort(leftHalf);
MergeSort(rightHalf);
return SortAndMerge(leftHalf,rightHalf);
}

public Int32[] SortAndMerge(Int32[] left, Int32[] right) {
Int32[] myResult = new Int32[left.Length+right.Length];
while (left.Length > 0 || right.Length > 0) {
if (left.Length > 0 && right.Length > 0)
{
if (left[0] <= right[0])
{
myResult[myResult.Length] = left[0];
int toRemoveIndex = Array.IndexOf(left, left[0]);
left = left.Where((x, y) => y != toRemoveIndex).ToArray();
}
else
{
myResult[myResult.Length] = right[0];
int toRemoveIndex = Array.IndexOf(right, right[0]);
right = right.Where((z, g) => g != toRemoveIndex).ToArray();
}

}
else if (left.Length > 0)
{
myResult[myResult.Length] = left[0];
int toRemoveIndex = Array.IndexOf(left, left[0]);
left = left.Where((x, y) => y != toRemoveIndex).ToArray();
}
else if (right.Length > 0) {
myResult[myResult.Length] = right[0];
int toRemoveIndex = Array.IndexOf(right, right[0]);
right = right.Where((x, y) => y != toRemoveIndex).ToArray();
}
}
return myResult;
}

最佳答案

if (array.Length == 0) return;

这绝不是真的,因此是异常(exception),因为您总是这样创建数组。

Int32[] leftHalf = new Int32[mid+1];

最小长度为1。

在此处查看正确的归并排序算法。

https://en.wikipedia.org/wiki/Merge_sort#Algorithm

关于c# - C# 中的简单归并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43315005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com