开发者

Method to merge two queues in a particular order

private ArrayQueue<E> merge( ArrayQueue<E> q1, ArrayQueue<E> q2 ) throws ArrayQueueException 
{
    开发者_C百科ArrayQueue<E> mergeQueue = new ArrayQueue<E>( q1.size() + q2.size() );

    ArrayQueue<E> smallestQueue = smallestQueue( q1, q2 );
    ArrayQueue<E> biggestQueue = biggestQueue( q1, q2 );

    for ( int index = 0; index < smallestQueue.size(); index++ )
    {
        E elementOne = smallestQueue.dequeue();
        E elementTwo = biggestQueue.dequeue();

        if ( elementOne.compareTo( elementTwo ) < 0 )
        {
            mergeQueue.enqueue( elementOne );
            mergeQueue.enqueue( elementTwo );
        }
        else
        {
            mergeQueue.enqueue( elementTwo );
            mergeQueue.enqueue( elementOne );
        }
    } 

    for ( int index = 0; index < biggestQueue.size(); index++ )
    {
        mergeQueue.enqueue( biggestQueue.dequeue() );
    }

    return ( mergeQueue );
}

I have been attemting an exercise which involves creating a method to merge two queues. My attempt above works when both queues are the same size however it is wrong otherwise.

What would be the best way to implement this?

Thanks.


That's not the only problem with your method.

Pseudocode of the correct method looks like this:

while (both queues are not empty) {
    retrieve first elements without removing them from their queues
    compare them
    put the appropriate element into the new queue and remove it from its old queue
}

if any of old queues is not empty, put its elements into the new queue
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜