All topics
33

Sorting by repeatedly picking the smallest

Tier 1Locked

Where it runs

1. The problem

You have a list of numbers in no particular order, and you want them from smallest to largest. A game lobby shows five players with scores 40, 15, 27, 8 and 31. You want the leaderboard in order, from the lowest score to the highest.

So far you searched a list for one value. Now you have to put the whole list in order. The simplest way to sort is to ask one question again and again: which number is the smallest among the ones not yet in their place?

Keep answering that question, and the list ends up sorted.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included
Insertion sort on six numbers
insertionSort([5, 2, 4, 6, 1, 3])
arr
5
2
4
6
1
3
key = -shifts = 0

Sort [5, 2, 4, 6, 1, 3] with insertion sort. The part on the left is sorted; at the start it is just 5.

Speed race
Selection, insertion and merge sort on the same 40 shuffled numbers

One operation is one comparison or one move. Every frame, each lane does the same number of operations, so the slow one falls behind.

Selection sort O(n²)
0 operations
Insertion sort O(n²)
0 operations
Merge sort O(n log n)
0 operations

 

And with more numbers

Operations for n numbers, and roughly how long they take at 100 million simple operations a second. An estimate from the same count, not a measurement.

n = 1,000
Selection sort500.5K · 5 ms
Insertion sort501.5K · 5 ms
Merge sort19.9K · under 1 ms
n = 100,000
Selection sort5B · 50 s
Insertion sort5B · 50 s
Merge sort3.3M · 33 ms
n = 10,000,000
Selection sort50T · 5.8 days
Insertion sort50T · 5.8 days
Merge sort465.1M · 4.7 s

Recognise it

Elementary sorts (selection, bubble, insertion)

Say these words and it is this pattern

  • n is small (tens or a few hundred)
  • array is nearly sorted already
  • sort in place with O(1) extra space
  • teaching/interview question about how sorting works
  • stability matters and simplicity is fine

Looks similar, isn't

n up to roughly 5000 is fine at O(n squared). Insertion sort drops to O(n) on nearly sorted data.

On LeetCode

Selection sort is too slow for LeetCode's large sorting tests, so these problems keep n small, at most a few thousand. They ask you to order a short list or compare a list with its sorted copy.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy