Lets say that I have sets that I know are already sorted such as {0,2,10,23,65} and {3,5,8..}. What would be the best sorting algorithm that could combine any number of pre-sorted sets into one sorted set? For how effecient would this type of sorting be?
Share
You do not need to sort them, you need to merge. This is done in
O(M+N)using a simple loop that keeps two indexes looking at the current element of the two parts, adding the smaller of the two to the final sequence, and advancing the index by one.Here is pseudocode:
At each step the loop advances either
iorj, executingparts1.Lenght + part2.Lengthtimes.