📚 The CoCalc Library - books, templates and other resources
License: OTHER
Empirical order of growth
Sometimes we can figure out what order of growth a function belongs to by running it with a range of problem sizes and measuring the run time.
order.py
contains functions from Appendix A we can use to estimate order of growth.
Comparing sort algorithms
NumPy provides implementations of three sorting algorithms, quicksort, mergesort, and heapsort.
Read about each of these algorithms to see what order of growth they belong to.
Now let's see if we can characterize their asymptotic behavior.
Quicksort is hard to distinguish from linear, up to about 10 million elements.
Merge sort is similar, maybe with some upward curvature.
The three methods are effectively linear over this range of problem sizes.
And their run times are about the same, with quicksort being the fastest, despite being the one with the worst asympotic performance in the worst case.
Implementing Merge Sort
This version breaks the array in half, uses np.sort
to sort the two halves, then uses merge to put the halves together.
Exercise: Write a function called merge
that takes two sorted NumPy arrays, left
and right
, and returns a new array that contains all elements from left
and right
, sorted. (where "sorted" means in ascending order, or non-decreasing, to be more precise).
Note: this function is not hard to write, but it is notoriously difficult to get all of the edge cases right without making the function unreadable. Take it as a challenge to write a version that is correct, concise, and readable.
Exercise: Starting with merge_sort_norec
, write a function called merge_sort_rec
that's fully recursive; that is, instead of using numpy.sort
to compute the DFTs of the halves, it should use merge_sort_rec
. Of course, you will need a base case to avoid an infinite recursion.
Test your method by running the code in the next cell, then use test_merge_sort_rec
, below, to check the performance of your function.
If things go according to plan, your implementation of merge sort should be close to linear, or a little steeper.