Skip to content

Sorting by Hand

You'll write four sorting algorithms from memory and time them on a million numbers, so you understand exactly why the built-in exists.

About

You'll never ship your own sort, and you'll write one anyway, because sorting is the cleanest way to feel the difference between n squared and n log n in your own hands. Bubble sort on a million items in Python runs all night, while merge sort finishes before you look up. Once you've waited for the slow one, you never forget it.

At a glance

Per requirement
35 XP
Completion bonus
300 XP
Requirements
6
Takes
Two weeks
Skill level
Intermediate (months of practice)
Cost
Free
Supplies
Nothing special
Where
At home
Other people
On your own
Locked for now
Earn two more Uncommon badges in Coding to open this one. Log in to see how far along you are.

Requirements

  1. 1
    Write bubble sort and insertion sort from memory, with tests against the built-in. No looking at references while you type. Test each one against your language's sort on 1,000 random lists, including an empty list, a single item, an already sorted list and a reverse sorted one. Take a screenshot of the tests passing. Photo
  2. 2
    Write merge sort and quicksort, and make quicksort survive sorted input. Naive quicksort with the first element as the pivot goes quadratic on sorted data. Pick a random pivot or the median of three instead. Test the sorted case at 100,000 items. Take a screenshot of the tests and the timing on sorted input. Photo
  3. 3
    Time all four on 1,000, 10,000, 100,000 and 1,000,000 random integers. Print a table. Bubble sort at a million in Python can take all night, so let it run while you sleep, or stop it after an hour and estimate from the 100,000 run. The table is the lesson. Take a screenshot of the table. Photo
  4. 4
    Explain the timings in terms of n squared and n log n, with the numbers. Going from 10,000 to 100,000 should make bubble sort about 100 times slower and merge sort about 13 times slower. Check your table against that and write out the math. Take a photo of the written explanation. Photo
  5. 5
    Implement binary search and show with a counter that it makes under 25 comparisons on a million items. Count every comparison. Log base 2 of a million is about 20. Also try it on an unsorted list and show that it gives wrong answers, because people forget that part. Take a screenshot of the counter output. Photo
  6. 6
    Sort 100,000 records by a field without copying the records. Sort indexes or references rather than the data itself. Then explain in two sentences why that matters when each record is a megabyte. Take a screenshot of the output and your note. Photo