Skip to the content

Selection sort

JavaScript · Unit 22: Searching and sorting

This is how a lot of people sort a handful of cards: find the smallest, put it at the front and repeat with what's left. That's selection sort.

You already know how to do the first part: a walk that keeps the position of the smallest.

const ns = [40, 10, 30];
let min = 0;
for (let i = 1; i < 3; i++) {
  if (ns[i] < ns[min]) {
    min = i;
  }
}
console.log(min, ns[min]);

Prints

1 10

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete it so smallestFrom gives the position of the smallest number from i onwards.

  2. 2. Put the lines in order

    Put in order the function that swaps the elements at positions i and j and returns the array.

  3. 3. Find the bug

    This should swap the first two and leave [ 10, 40, 30 ]. Which line has the error?

  4. 4. Predict the output

    The array gets printed after each pass. What does it print?

  5. 5. Complete the code

    Complete it so each pass looks for the smallest only among the ones still left.

  6. 6. Find the case that fails

    smallest(ns) returns the smallest number in the list, or 0 if the list is empty. Which call does it fail on?

  7. 7. Predict the output

    comps counts comparisons between numbers. What does it print?

  8. 8. Multiple choice

    You hand selection sort a list that already came sorted. What does it do?

  9. 9. Predict the output

    The function swaps two positions and returns the array. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →