salam
salam

Reputation: 37

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

Upvotes: 1

Views: 1684

Answers (1)

Hossein Golshani
Hossein Golshani

Reputation: 1897

try this edited version: (note that your code is also sort input parameter '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:

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;
}

Upvotes: 2

Related Questions