简体   繁体   English

在 Java 中使用队列对元素进行排序

[英]Sorting Elements using Queue in Java

I am trying to sort elements(Integers) present in queue, using another queue.我正在尝试使用另一个队列对队列中存在的元素(整数)进行排序。 Queue does not have negative numbers or duplicate values Queue must sorted in ascending order.(head -> tail) sample input:4 [7 3 9 5]队列没有负数或重复值队列必须按升序排序。(头 -> 尾)样本输入:4 [7 3 9 5]

output: [3 5 7 9]输出:[3 5 7 9]

import java.util.*;

public class Source {
public static void main(String args[]) {
    Queue<Integer> queue = new LinkedList<Integer>();
    Scanner s = new Scanner(System.in);
    int n = s.nextInt();
    while (n-- > 0)
        queue.add(s.nextInt());
    sort(queue);
}

// Method to sort the queue
static void sort(Queue<Integer> queue) {
    Queue<Integer> queue2 = new LinkedList<Integer>();
    queue2.add(queue.remove());
    while(queue.size()!=0){
    int temp = queue.remove();
   queue2.add(temp);
    while(temp<queue2.peek()){
        queue2.add(queue2.remove());
    }
    }
    System.out.println(queue2);
}

} }

Since you have no negative numbers in the queue I was thinking doing as follows:由于队列中没有负数,我想这样做:
1. insert a negative number to the first queue (the "dummy" technique). 1. 在第一个队列中插入一个负数(“虚拟”技术)。
2. Search for the minimum number in the first queue until you hit the dummy. 2. 搜索第一个队列中的最小数字,直到遇到假人。
3. Remove the dummy. 3. 取下假人。
4. Search in the queue for the minimum value that you found in step 2, remove it and insert it to the second queue. 4. 在队列中搜索您在步骤 2 中找到的最小值,将其删除并将其插入到第二个队列中。
5. Follow these 4 steps until the first queue is empty. 5. 按照这 4 个步骤,直到第一个队列为空。

Java code:爪哇代码:

static void sort(Queue<Integer> q1) {
    Queue<Integer> q2 = new Queue<Integer>();
    int min=Integer.MAX_VALUE;
    while (!q1.isEmpty())
    {
        q1.insert(-1);
        while(q1.head() != -1)
        {
            if (q1.head() < min)
            {
                min=q1.head();
            }
            q1.insert(q1.remove());

        }
        q1.remove(); //removing the -1
        while (q1.head() != min)
        {
            q1.insert(q1.remove());
        }
        min = Integer.MAX_VALUE;
        q2.insert(q1.remove()); //inserting the minimum to the second queue.
    }
    System.out.println(q2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM