Sorting a dynamic queue in c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Sorting a dynamic queue in c++

I just started learning about stacks, queues and decks. From what I've seen so far from my textbooks and from the internet, I've grasped the way a queue works. I'm trying to solve a problem that I got as a homework so I'm not asking for the entire solution, I just want an advice how to go about said problem. What I'm trying to do is to take 2 dynamic queues and sort them by size of the elements and then pop said elements into a third queue that also is going to get sorted. The easiest way for me would've been to pop all of the elements into an array to sort them and then to push them into the queue, however part of the task was to not use any extra space. I've thought of ways to do that and here's what I came up with: each queue will get sorted separately by popping 2 of its elements, then comparing them, and pushing the smaller one back in while keeping the bigger one to compare it to the next element of the queue. By the n-th rotation they should've gotten sorted. What confuses me is how to do the function that is going to compare them.

3rd Apr 2020, 12:00 PM
Potatogroup
Potatogroup - avatar
2 Answers
+ 2
I do not understand how that helps with the third record. Popping once more would retrieve the already sorted value and you would not have storage available to see that third. Assuming you have a method to loop through all records in the queue, you only need one extra record to do a swap. if (queue[first] > queue[second]) { temp = queue[first]; queue[first] = queue[second]; queue[second] = temp; }
3rd Apr 2020, 9:37 PM
John Wells
John Wells - avatar
+ 2
Once the originals are sorted, you just need to push the records onto the third queue in order from which ever queue has the next record needed to maintain the sort.
3rd Apr 2020, 9:43 PM
John Wells
John Wells - avatar