* @return target sorted queue
* @throws IOException exception thrown if there is IO error during the operation
*/
public static IBigQueue nWayMergeSort(List<IBigQueue> listOfSortedQueues) throws IOException {
String newQueueName = getNextTempQueueName();
IBigQueue targetBigQueue = new BigQueueImpl(SAMPLE_DIR, newQueueName); // target queue
int ways = listOfSortedQueues.size();
long begin = System.currentTimeMillis();
while(true) {
IBigQueue queueWithLowestItem = null;
String lowestItem = null;
// find the lowest item in all n way queues
for(IBigQueue bigQueue : listOfSortedQueues) {
if (!bigQueue.isEmpty()) {
if (queueWithLowestItem == null) {
queueWithLowestItem = bigQueue;
lowestItem = new String(bigQueue.peek());
} else {
String item = new String(bigQueue.peek());
if (item.compareTo(lowestItem) < 0) {
queueWithLowestItem = bigQueue;
lowestItem = item;
}
}
}
}
if (queueWithLowestItem == null) break; // all queues are empty
// extract and put the lowest item into the target queue
byte[] data = queueWithLowestItem.dequeue();
targetBigQueue.enqueue(data);
}
// release the source queues since we have done with them
for(IBigQueue bigQueue : listOfSortedQueues) {
bigQueue.removeAll(); // make empty the queue, delete back data files to save disk space
bigQueue.close();
}
targetBigQueue.close();
long end = System.currentTimeMillis();
output("Time used to merge sort " + ways + " way queues : " + (end - begin) + " ms.");