排序不正常

时间:2015-03-23 14:08:11

标签: c# sorting

我试图弄清楚为什么会这样,但是当我能够解决它周围的数字时。代码假设要做的是有两个堆栈,程序假设按升序排序,它会这样做,但是如果我改变了:

first.Push(7)

类似

first.Push(80) 

它没有用。 有人可以解释一下吗? 这就是我所拥有的:

using System;
using System.Collections;

namespace Project03_03
{
   class Program
   {
      static void Main(string[] args)
      {
          Stack first = new Stack();
          first.Push(50);
          first.Push(45);
          first.Push(11);
          first.Push(7);

          Stack second = new Stack();
          second.Push(67);
          second.Push(65);
          second.Push(32);
          second.Push(12);

          ProcessInOrder(first, second);

          Console.WriteLine(
              "Press any key to continue...");
          Console.ReadKey();
      }

      static void ProcessInOrder(Stack first,
          Stack second)
      {
          while (first.Count > 0 || second.Count > 0)
          {
              if (first.Count == 0)
              {
                  Console.WriteLine(second.Pop());
                  continue;
              }

              if (second.Count == 0)
              {
                  Console.WriteLine(first.Pop());
                  continue;
              }

              if ((int)first.Peek()
                  >= (int)second.Peek())
              {
                  Console.WriteLine(
                      second.Pop());
              }
              else
              {
                  Console.WriteLine(first.Pop());
              }
          }

      }
  }
}

1 个答案:

答案 0 :(得分:1)

你的代码正在做的是合并两个已经排序的堆栈。所以它几乎只是遍历堆栈并查看哪个值更小然后显示那个值。因此,您有两个已经排序的堆栈,它可以将它们合并到一个也已经排序的较大堆栈中。

通过更改你的代码使得推入第一个堆栈的最后一个项目是80 vs 7,它会破坏这个状态,因此你的逻辑是有缺陷的。解决此代码的另一种方法可能是首先合并两个堆栈然后弹出它们并在那时对它们进行排序。 Here is a some code to sort a stack (dont click it if you want to try and figure it out yourself first)

您还可以编写一些单元测试,以确认在修改代码时修复了这些方案。

最后,如果您将新的排序代码与其中一个示例进行比较,则可以measure the difference in performance between the two like this example did