All episodes · From a List to Your Map App · Episode 6

Sorting by Hand: Insertion, Selection and Bubble Sort

Pressing play loads the video from YouTube.

Eight towers, three ways to sort them, and you could do every one of them by hand. They all get the same answer, but give them a thousand items and they need up to half a million comparisons.
We run insertion sort, selection sort and bubble sort step by step, count every comparison (7 + 6 + … + 1 = 28 for eight items, about n² ÷ 2 in general), see when insertion sort is quick, and find out what a "stable" sort is.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

Eight towers, out of order. Here are three ways to sort them, and you could do every one of them by hand. They all get the same answer. But give them a thousand items, and they need up to half a million comparisons. Today: three simple sorts, and why simple isn't fast.

First, insertion sort. It's how most people sort books on a shelf. Take the next one, and slide it left past every taller one, until it fits into the sorted part on the left. One by one, the sorted part grows, until it covers the whole row. A clever upgrade called Shell sort first compares items far apart, then closer and closer. We'll leave it at that.

Second, selection sort. Scan everything that's left, find the smallest, and put it at the front. Then scan the rest again for the next smallest, and the next. It always makes the same number of comparisons, even if the row was already sorted.

Third, bubble sort. Compare neighbors, and swap them if they're in the wrong order. After one pass, the tallest tower has bubbled all the way to the end. Repeat, and each pass settles one more tower. If a pass makes no swaps at all, you can stop early.

Now count. With eight towers, selection sort makes twenty-eight comparisons: seven, plus six, plus five, and so on. That's about n squared over two. For a thousand items, almost half a million comparisons. Insertion sort is quick when the row is almost sorted already. But on shuffled data, all three grow like n squared. One more idea: a stable sort keeps equal items in their original order. Insertion and bubble sort are stable. Selection sort, as usually written, is not.

Three simple sorts: easy to write, fine for small lists, but n squared when lists get big. Next time, a way to do much better: split the list in half, sort each half, and merge them. Merge sort. See you there.

Next episode: merge sort, which splits the list in half and does much better.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal