2

We were tasked to sort a queue in O(n log n) using basic functions such as enqueue, dequeue, peek, empty only. Additionally, we may use another queue to help us. No other data structures are allowed.

Having trouble coming up with a solution as I feel like this is possibly an modification of a divide-and-conquer problem but I am unable to come up with a solution using the 4 basic functions.

Is it possible to receive some hints to solve this problem?

9
  • By enqueue and dequeue you mean basic push and pop? Commented Sep 29, 2021 at 16:21
  • Yup, enqueue == push and dequeue == pop Commented Sep 29, 2021 at 16:26
  • 1
    Yup. For example a queue, q, with elements {1, 2, 3, 4}. q.push(5), elements = {1, 2, 3, 4 ,5} q.pop(), elements = {2, 3, 4, 5} Commented Sep 29, 2021 at 16:34
  • 1
    You can do a merge sort using queues. Commented Sep 29, 2021 at 16:37
  • 1
    Are any variables allowed other than the 2 queues? Commented Sep 29, 2021 at 17:16

1 Answer 1

10

Given queue A full and queue B empty, if A consists of sorted groups of w elements, then you can merge them in pairs to produce sorted groups of 2w elements as follows:

  1. While(A.length - B.length > w), pull w elements out of A and put them in B. A and B will then both consist of sorted groups of w elements, plus some left over.

  2. repeatedly pull w elements from both A and B, merging them onto the back of A to create sorted groups of 2w elements. Stop when all the elements have been processed (be careful not to pull elements from A that you already processed. You'll need to remember its original size). A will then consist of of sorted 2w groups, and B will be empty again.

Repeat the above procedure with w=1 (groups of 1 are always sorted), then w=2, w=4 ... w=2n, etc. until the whole queue is sorted.

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

1 Comment

this is a nice way to think of merge sort in general

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.