

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Sorting Algorithms
incomplete
2: Bubble Sort
incomplete
3: Bubble Sort Big O
incomplete
4: Why Bubble Sort?
incomplete
5: Merge Sort
incomplete
6: Merge Sort Big O
incomplete
7: Why Merge Sort?
incomplete
8: Insertion Sort
incomplete
9: Insertion Sort Big O
incomplete
10: Why Use Insertion Sort?
incomplete
11: Quicksort
incomplete
12: Quicksort Big O
incomplete
13: Fixing Quicksort
incomplete
14: Why Use Quicksort?
incomplete
15: Selection Sort
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Merge sort is a recursive sorting algorithm and it's quite a bit faster than bubble sort. It's a divide and conquer algorithm.:
Divide: divide the large problem into smaller problems, and recursively solve the smaller problems
Conquer: Combine the results of the smaller problems to solve the large problem
In merge sort we:
Divide the array into two (equal) halves (divide)
Recursively sort the two halves
Merge the two halves to form a sorted array (conquer)
The algorithm consists of two separate functions, merge_sort() and merge().
merge_sort() divides the input array into two halves, calls itself on each half, and then merges the two sorted halves back together in order.
The merge() function merges two already sorted lists back into a single sorted list. At the lowest level of recursion, the two "sorted" lists will each only have one element. Those single element lists will be merged into a sorted list of length two, and we can build from there.
In other words, all the "real" sorting happens in the merge() function.
Input: A, an unsorted list of integers
If the length of A is less than 2, it's already sorted so return it
Split the input array into two halves down the middle
Call merge_sort() twice, once on each half
Return the result of calling merge(sorted_left_side, sorted_right_side) on the results of the merge_sort() calls
Inputs: A and B. Two sorted lists of integers
Create a new final list of integers.
Set i and j equal to zero. They will be used to keep track of indexes in the input lists (A and B).
Use a loop to compare the current elements of A and B:
While i < len(A) and j < len(B), compare A[i] and B[j].
Append the smaller or equal value to final.
Increment the index for the list you just took from.
Stop when either list is exhausted.
After comparing all the items, there may be some items left over in either A or B. Add those extra items to the final list.
Return the final list.
Our LockedIn influencers are complaining that when they sort their followers by follower count, it gets really slow if they have more than 1,000 followers (because we're using Bubble Sort). Let's speed it up for them with merge sort.
Complete the merge_sort and merge functions according to the described algorithms.