[英]sorting the numbers in queue
so I have a question on queue. 所以我有一个问题要排队。 I need to build a function that takes a queue and returns it sorted from the smallest to the biggest value. 我需要构建一个接受队列并返回从最小到最大排序的函数。 I wrote a function to find me the smallest number in a queue without changing the queue itself ( checked this one , it works) and then i wrote this : 我写了一个函数来查找我队列中最小的数字,而无需更改队列本身(选中此按钮,它可以工作),然后我这样写:
static Queue<int> Order(Queue<int> q)
{
int x;
Queue<int> help = new Queue<int>();
while (!q.IsEmpty())
{
if (q.Head() == Small(q))
help.Insert(q.Remove());
else
{
x = q.Remove();
q.Insert(x);
}
Order(q);
}
while (!help.IsEmpty())
q.Insert(help.Remove());
return (q);
} }
and I really can't see where I messed because it dosent work.. so any suggestion? 而且我真的看不到我在哪里乱了,因为它工作得很好..所以有什么建议吗? ps : I work on c# 2010 , and sorry for bad English ps:我从事的是c#2010,对不起,英语不好
try this edited version: (note that your code is also sort input parameter 'q') 尝试使用此编辑版本:(请注意,您的代码也对输入参数'q'进行了排序)
static Queue<int> Order(Queue<int> q)
{
int x;
Queue<int> help = new Queue<int>();
while (q.Count > 0)
{
if (q.Peek() == q.Min())
help.Enqueue(q.Dequeue());
else
{
x = q.Dequeue();
q.Enqueue(x);
}
Order(q);
}
while (help.Count > 0)
q.Enqueue(help.Dequeue());
return (q);
}
but you can also use LINQ as follow to get sorted queue: 但您也可以按照以下方式使用LINQ来获得排序队列:
static Queue<int> Order(Queue<int> q)
{
Queue<int> q2 = new Queue<int>();
foreach (int i in q.OrderBy(x => x))
q2.Enqueue(i);
return q2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.