简单的合并排序不能正确地通过数组递归

时间:2015-01-01 20:32:10

标签: c# arrays sorting recursion mergesort

我正在尝试将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;
        }

1 个答案:

答案 0 :(得分:1)

decimal centerDcl = left + Convert.ToInt32(right)/2;

这似乎不对。

应该是:

decimal centerDcl = (left + Convert.ToInt32(right))/2;