任何人都可以帮忙告诉我为什么我的MergeSort不会排序列表?

时间:2013-10-25 18:40:49

标签: c# sorting comparison mergesort

让我的Merge Sort工作时遇到一些问题。如果有人可以帮助我,我会很感激。

我不知道为什么,但排序中出现的列表没有排序。我尝试过使用断点,但这似乎没有帮助找到问题。

static class MergeSort
{
    //Sort<T> - The <T> is called a generic parameter
    public static IList<T> Sort<T>(IList<T> input)
    {
        List<T> Result = new List<T>();
        Queue<T> Left = new Queue<T>(); //Switched from lists to queues because removing at index 0 is more efficient
        Queue<T> Right = new Queue<T>();
        //Dequeue() and Count() have a time complexity of O(1)

        if (input.Count <= 1)
            return input;

        int midpoint = input.Count / 2;

        for (int i = 0; i < midpoint; i++)
            Left.Enqueue(input[i]);
        for (int i = midpoint; i < input.Count; i++)
            Right.Enqueue(input[i]);

        Left = new Queue<T>(Sort(Left.ToList())); //Recursion! :o
        Right = new Queue<T>(Sort(Right.ToList())); ; //This line and the one above split the list into smaller lists (left and right)

        Result = Merge(Left, Right); //This joins the lists together

        return Result;
    }

    private static List<T> Merge<T>(Queue<T> Left, Queue<T> Right)
    {
        List<T> Result = new List<T>();
        while (Left.Count /* O(1) operation */ > 0 && Right.Count > 0)
        {
            int cmp = Comparison((Left.Peek() as Entity), (Right.Peek() as Entity));
            //If cmp is less than 0, left is less. If it is greater, left is greater

            if (cmp < 0)
                Result.Add(Left.Dequeue());
            //Left.RemoveAt(0) - Using a list to remove at a certain point is inefficient
            else
                Result.Add(Right.Dequeue());
        }

        while (Left.Count > 0)
            Result.Add(Left.Dequeue());

        while (Right.Count > 0)
            Result.Add(Right.Dequeue());

        return Result;
    }

    private static int Comparison(Entity Left, Entity Right)
    {
        if (Left.TimesEaten > Right.TimesEaten)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }
}

如果您需要知道,在“比较”方法中,Left.TimesEaten是一个整数。

2 个答案:

答案 0 :(得分:1)

Merge实施中存在错误。对于给定的LeftRight队列,您只需比较他们的第一个元素。实际上,您需要在每次添加后重新执行比较(例如,通过在循环中移动Comparison调用):

private static List<T> Merge<T>(Queue<T> Left, Queue<T> Right)
{
    List<T> Result = new List<T>();
    while (Left.Count > 0 && Right.Count > 0)
    {
        int cmp = Comparison((Left.Peek() as Entity), (Right.Peek() as Entity));
        //If cmp is less than 0, left is less. If it is greater, left is greater

        if (cmp < 0)
            Result.Add(Left.Dequeue());
        else
            Result.Add(Right.Dequeue());
    }

    // ...

答案 1 :(得分:1)

int cmp = Comparison((Left.Peek() as Entity), (Right.Peek() as Entity));

必须在while循环中。整个合并使用来自相同比较的结果。