C#中的简单合并排序

时间:2017-04-10 04:29:03

标签: c# algorithm sorting mergesort

我一直在对排序算法做一个小修改,并且遇到了Merge Sort。我编写了我的代码,并在最后一小时修改它,确定它为什么还没有工作。我正在获得标准的StackOverFlow Exception。任何人都可以告诉我这个算法有什么问题吗?提前致谢。这就是我到目前为止所写的内容:

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;
}

2 个答案:

答案 0 :(得分:2)

if (array.Length == 0) return;

这是永远不会的,因此是例外,因为你总是像这样创建数组。

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

最小长度为1。

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

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

答案 1 :(得分:1)

你介意重构吗?为什么不使用zip 这里是来自msdn的样本

teamMems = members.map((member, i) => (
  <TeamMember key={i} {...this.props} member={member}>
)

此代码生成以下输出:

1个

2两个

3三

还有linq for sort。