Bitpath

Lesson 2 · Unit 02

Insertion sort

Slide each item into place; nearly sorted input is nearly free

12 exercisesabout 3 min

What you practise

  • Shift and insert
  • O(n) on nearly sorted input

Try a question from this lesson

Pick one

You hold the cards 3, 5, 9 in order and draw a 4. What is the least work that puts your hand back in order?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Insertion sort

Keep the left part of the list sorted and grow it one item at a time.

Take the next item x. Walk left through the sorted part, copying each larger value one place right. Stop at a value that is not larger, or at the front, and write x into the gap.

def insertion_sort(a):
    for i in range(1, len(a)):
        x = a[i]
        j = i - 1
        while j >= 0 and a[j] > x:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = x
    return a
function insertionSort(a) {
  for (let i = 1; i < a.length; i++) {
    const x = a[i];
    let j = i - 1;
    while (j >= 0 && a[j] > x) {
      a[j + 1] = a[j];
      j--;
    }
    a[j + 1] = x;
  }
  return a;
}
function insertionSort(a: number[]) {
  for (let i = 1; i < a.length; i++) {
    const x = a[i];
    let j = i - 1;
    while (j >= 0 && a[j] > x) {
      a[j + 1] = a[j];
      j--;
    }
    a[j + 1] = x;
  }
  return a;
}

Python noteand short-circuits: when j is -1, a[j] > x is never evaluated.

TypeScript noteconst x = a[i] is const because x never changes; let j is reassigned by j--. TypeScript infers number for both.

10 more exercises in the app

  • 2× type the answer
  • 4× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× order the lines
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy