Python 3D Academyবাংলা

Fast Sorts in Python

Chapter 45: Fast Sorts

5 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. Merge sort: merging two sorted piles

    Merge sort splits the list in half, sorts each half the same way, and merges the two sorted halves by repeatedly taking the smaller of their front values.

  2. Quick sort: partitioning around a pivot

    Quick sort partitions the list around a pivot, so the pivot lands in its final place with smaller values on its left and the rest on its right, then quick sorts each side.

  3. Counting sort: beating n log n when the keys are small

    When every key is a small whole number from 0 to k − 1, count how many times each key appears, then write the keys out in order as many times as they were counted.

  4. Python's sort(): Timsort, key=, sorting objects, and choosing a sort

    Timsort finds the runs that are already in order, makes short ones longer with insertion sort, and merges the runs with merge sort's merge, so it is stable, O(n log n) at worst, and close to O(n) on nearly sorted lists.

  5. Quickselect and bucket sort: when sorting everything is too much

    Quickselect partitions around a pivot exactly as quick sort does, but then follows only the side that holds position k, so on average it does about 2n comparisons instead of n log n; bucket sort puts each value into a bucket chosen from the value itself (here, its count), so reading the buckets in order needs no comparisons at all.