View the step-by-step solution to:


We want to sort a sequence of numbers using a stack. We imagine the numbers arrive at the stack in their input

order. For example, if the input is 5,1,4,2,3 then 5 arrives first and 3 arrives last. When a number arrives, we must push it onto the stack and then we can perform any number of pop operations (including none). Each pop operation not only pops the top number off of the stack it also outputs the number. Pops on an empty stack are invalid. We want the sequence of numbers that are output to be the original input sequence in non-decreasing order.

For example, the following operation sequence sorts 5,1,4,2,3: IIOIIOIOOO where I means "push In" and O means "pop Out".

Suppose we add the choice of a queue to our sorting algorithm. Now we can use the operations I, O, E, and D, where I and O push and pop the stack, while E and D enqueue and dequeue the queue (dequeue also outputs the number that is dequeued). For example, we can sort 5,1,4,2,3 using: IEIEEDDDOO.

  1. Q1 Is it possible to sort all input sequences using such a stack and queue? If yes then explain how. If no, give a permutation that cannot be output.


Suppose we add two new operations.

S : pop a number from the stack (without output) and enqueue it into the queue; and

  Q : dequeue a number from the queue (without output) and push it onto the stack.

Is it possible to sort all input sequences using the operations I, O, E, D, S, and Q? If yes then explain how. If no, give a permutation that cannot be output.

Recently Asked Questions

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question
Ask Expert Tutors You can ask 0 bonus questions You can ask 0 questions (0 expire soon) You can ask 0 questions (will expire )
Answers in as fast as 15 minutes