Упорядочить элементы числового массива в порядке возрастания с помощью стека и линейного списка - C#
Формулировка задачи:
Упорядочить элементы числового массива в порядке возрастания с помощью стека и линейного списка.
помогите
Решение задачи: «Упорядочить элементы числового массива в порядке возрастания с помощью стека и линейного списка»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
namespace SortedByStack
{
class Program
{
private static List<int> GetNonSortedList(int count)
{
if(count < 0)
throw new ArgumentException("count can't be negative", "count");
var result = new List<int>();
if (count == 0) return result;
var elementGenerator = new Random();
while (result.Count < count)
result.Add(elementGenerator.Next(100));
return result;
}
private static void ExchangeValueFromListToStack<T>(int index, Stack<T> stack, IList<T> list) where T : struct
{
if(stack == null)
throw new ArgumentNullException("stack");
if(list == null)
throw new ArgumentNullException("list");
if(index > list.Count)
throw new Exception();
stack.Push(list.ElementAt(index));
list.RemoveAt(index);
}
private static Stack<T> GetSortedStackFromNonSortedList<T>(IList<T> nonSortedList) where T : struct, IComparable<T>
{
var stack = new Stack<T>();
var count = nonSortedList.Count;
for (var j = 0; j < count; j++)
{
ExchangeValueFromListToStack<T>(0, stack, nonSortedList);
for (var i = 0; i < nonSortedList.Count; i++)
{
var currentElement = stack.Peek();
if (currentElement.CompareTo(nonSortedList.ElementAt(i)) >= 0)
{
var tempEl = stack.Pop();
ExchangeValueFromListToStack(i, stack, nonSortedList);
nonSortedList.Insert(i, tempEl);
}
}
}
return stack;
}
private static void Main()
{
const int count = 15;
var nonSortedList = GetNonSortedList(count);
Console.WriteLine("Non sorted: ");
nonSortedList.ForEach(el => Console.Write(" {0} ", el));
var stack = GetSortedStackFromNonSortedList(nonSortedList);
Console.WriteLine("{0}Sorted: ", Environment.NewLine);
foreach (var element in stack)
Console.Write(" {0} ", element);
}
}
}