public void Test36() { var sortAscending = new MyStackSortAscending <int>(); for (int i = 0; i < 11; i++) { sortAscending.Push(i); } MyStackSortAscending <int> ints = MyStackSortAscending <int> .SortAscending(sortAscending); for (int i = 10; i >= 0; i--) { Assert.AreEqual(i, ints.Pop()); } }
/// <summary> /// Biggest on the top O(N^2) + O(N) space /// </summary> /// <param name="stack"></param> /// <returns></returns> public static MyStackSortAscending <T> SortAscending(MyStackSortAscending <T> stack) { if (stack.IsEmpty() || stack.Count == 1) { return(stack); } var result = new MyStackSortAscending <T>(); while (!stack.IsEmpty()) { T tmp = stack.Pop(); while (!result.IsEmpty() && result.Peek().CompareTo(tmp) > 0) { stack.Push(result.Pop()); } result.Push(tmp); } return(result); }