Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a queue in O(n log n) using at most 2 queue

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?

like image 387
Math.anony Avatar asked Jan 21 '26 22:01

Math.anony


1 Answers

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.

like image 137
Matt Timmermans Avatar answered Jan 23 '26 19:01

Matt Timmermans