简单的合并排序不能正确地递归数组
Simple merge sort not recursing through array correctly
我正在尝试将 simple merge sort algorithm found here 移植到 C# 作为学术练习。我相信 我遵循了他们的代码,但是递归条件是错误的。
我相信我正确地递归到树的左侧(?),但是当我到达后半部分时,它进入了无限循环。如何让递归继续处理数组?
当我进入下半场时,输出是:
11, 1, 5
11, 1, 3
11, 1, 2
11, 1, 1
11, 4, 6
11, 4, 6
11, 4, 6
11, 4, 6
密码是:
var input = new[] {5, 10, 1, 7, 9, 15, 8, 11, 20, 2};
var result = MergeSort.Sort(input);
using System;
using System.Diagnostics;
namespace MergeSort {
internal class MergeSort
{
public static int[] Sort(int[] input, int left = 0, int? rightNullable = null)
{
var right = (rightNullable == null)
? input.Length - 1
: Convert.ToInt32(rightNullable);
if (left >= right) { return input; }
decimal centerDcl = left + Convert.ToInt32(right)/2;
var center = Convert.ToInt32(centerDcl);
Console.WriteLine("{0}, {1}, {2}", input.Length + 1, left + 1, center + 1);
Debug.WriteLine("{0}, {1}, {2}", input.Length + 1, left + 1, center + 1);
Sort(input, left, center);
Sort(input, center + 1, rightNullable);
input = Merge(input, left, center + 1, right);
return input;
}
decimal centerDcl = left + Convert.ToInt32(right)/2;
这似乎不对。
应该是:
decimal centerDcl = (left + Convert.ToInt32(right))/2;
我正在尝试将 simple merge sort algorithm found here 移植到 C# 作为学术练习。我相信 我遵循了他们的代码,但是递归条件是错误的。
我相信我正确地递归到树的左侧(?),但是当我到达后半部分时,它进入了无限循环。如何让递归继续处理数组?
当我进入下半场时,输出是:
11, 1, 5
11, 1, 3
11, 1, 2
11, 1, 1
11, 4, 6
11, 4, 6
11, 4, 6
11, 4, 6
密码是:
var input = new[] {5, 10, 1, 7, 9, 15, 8, 11, 20, 2};
var result = MergeSort.Sort(input);
using System;
using System.Diagnostics;
namespace MergeSort {
internal class MergeSort
{
public static int[] Sort(int[] input, int left = 0, int? rightNullable = null)
{
var right = (rightNullable == null)
? input.Length - 1
: Convert.ToInt32(rightNullable);
if (left >= right) { return input; }
decimal centerDcl = left + Convert.ToInt32(right)/2;
var center = Convert.ToInt32(centerDcl);
Console.WriteLine("{0}, {1}, {2}", input.Length + 1, left + 1, center + 1);
Debug.WriteLine("{0}, {1}, {2}", input.Length + 1, left + 1, center + 1);
Sort(input, left, center);
Sort(input, center + 1, rightNullable);
input = Merge(input, left, center + 1, right);
return input;
}
decimal centerDcl = left + Convert.ToInt32(right)/2;
这似乎不对。
应该是:
decimal centerDcl = (left + Convert.ToInt32(right))/2;