Written by PChan on 2017-04-14
Key Idea: Sorting Two Sorted Lists¶
In this section, we would discuss how to sort two given lists that are already sorted. The goal here is to take advantage that the two lists are already sorted; we want to avoid sorting the combined list.
Given the following lists:
A = [1, 3, 5, 7, 9] B = [2, 4, 6, 8, 10]
Jot down on a piece of paper an algorithm for sorting the two lists. Test out your algorithm and revise it if necessary.
- Compare the first element of both lists
- Remove the smaller of the two and insert it into a new list
- Repeat steps 1 and 2 while both lists are non-empty
- If one list is empty, append its remaining element to the new list in the exact same order
- Once both lists are empty, the new list should contain the elements of both lists in ascending order
The General Algorithm¶
Once you have gotten down the merging routine, the rest of the mergesort algorithm is very simple.
- If the size of the given list is 1, return that list
- Otherwise, split the given list in half
- Repeat steps 1 and 2 for each sublist until they are of size 1
- Merge each half together using the algorithm discussed above
Here are some questions to ponder over (in order of ascending difficulty):
- Is there a best case scenario? A worst case scenario?
- How many times do you need to half the list before you can start merging?
- What disadvantage(s) does mergesort have compared to other sorting algorithms?
- How might splitting and remerging the list be faster than selection sort or insertion sort?
- Determine the runtime of this algorithm. What is the ratio of the time it takes to sort the list and the size of the list?