1

I dont know if this is possible at all but:

Say we got 2 queues: queue1 and queue2, and each queue includes (natural) numbers that are sorted from lowest to greatest (queue1.head() and queue2.head() return the smallest value of queue1 / queue2).

How could you output the numbers that are included in queue1 and queue2 in sorted (from lowest to greatest) order without using additional data structure?

1
  • google("merge sort") Commented May 6, 2016 at 16:49

2 Answers 2

3

Like this:

while (!queue1.isEmpty() || !queue2.isEmpty()) {
     if (queue1.isEmpty()) {
         System.out.println(queue2.remove());
     } else if (queue2.isEmpty()) {
         System.out.println(queue1.remove());
     } else if (queue1.peek() < queue2.peek()) {
         System.out.println(queue1.remove());
     } else {
         System.out.println(queue2.remove());
     }
}

First you need to take the case when one of queues is empty, so then you output from other. Then you peek in both and compare them and take the smallest. You do this until both queues are empty.

Sign up to request clarification or add additional context in comments.

Comments

0

If you don't mind adding stuff to the first queue:

queue1.addAll(queue2);
queue1.stream().sorted(Integer::compare).forEach(System.out::println);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.