How to Sort and Merge Multiple Queues in Java

Java Assignment Details

java assignmentTo sort and merge multiple queues, where the input queues were to be read from a file.

How to Solve Such Problems in Java

Sort and Merge Multiple QueuesFirst of all, to start with Java assignment we have to look at the requirement. What is provided to us, what is needed to do. In programming there are plenty of way to do the same thing but we need to identify which way to use in specific condition is better. Once we decide the approach we start creating a pseudo code which has the overall map of entire program. Here we need to take care of all the situations where this may fail so we need to identify all the loopholes and cover up all them before actual implementation. Then we start working on implementing actual Java code.

Java Assignment Solution

  • Read a filename from user.
  • Read the file line wise.
  • Process the file and store the available queues as unsorted queue in a list
  • Process each queue and sort them.
  • Store the sorted queue in a new Array of Lists
  • Merge the sorted queues & display the final result.
Sort and Merge Multiple Queues easy

image credit:

Expert’s Approach

We need to read a file and store the queues, used the readList method() from FileLine class (modified to return the processed output queues). And then to sort the queue used an algorithm:

while not unsortedqueue.isEmpty() do
                           smallest = unsortedqueue.dequeue() ;
                      queuelength = unsortedqueue.length() ;
                      For i = 1 to queuelength do
                                         element = unsortedqueue.dequeue() ;
                                         if smallest > element then
                                                        unsortedqueue.enqueue(smallest) ;
                                                    smallest = element ;
                                                        unsortedqueue.enqueue(element) ;
                           sortedqueue.enqueue(smallest) ;
          The output was a List of sorted queues

Processing this output list and merging them into one sorted output list using the following algorithm:

totalelements = 0
for each linkedqueue in sortedqueue do
totalelements += linkedqueue.size()
end for
while result.size()<totalelements do
lowestqueue=null, i=0
for each linkedqueue in sortedqueue do
if  linkedqueue is not empty then
if lowestqueue == null then
lowestqueue = linkedqueue;
else if linkedqueue.first() <= lowestqueue.first() then
lowestqueue = linkedqueue;
end if
end if
end for

Display the output.

Got a similar complex Java problem? Let our experts deal with it!