Sikau

Algorithms · Day 2 · about 30 min

Sorting basics

Insertion sort, comparators, stability and what .sort() really does.

The number 10 comes before 9?

[10, 9, 1].sort() gives [1, 10, 9] — JavaScript compares as text unless you pass a comparator. Sorting is everywhere (leaderboards, menus by price, search results), so knowing how it works and how to control it pays off daily.

Insertion sort and comparators

function insertionSort(arr, compare = (a, b) => a - b) {
  const a = arr.slice();
  for (let i = 1; i < a.length; i++) {
    const item = a[i];
    let j = i - 1;
    while (j >= 0 && compare(a[j], item) > 0) {
      a[j + 1] = a[j];
      j--;
    }
    a[j + 1] = item;
  }
  return a;
}

console.log([10, 9, 1].sort());
console.log(insertionSort([10, 9, 1]));

const dishes = [
  { name: "Momo", cat: "starter", price: 180 },
  { name: "Tea", cat: "drink", price: 50 },
  { name: "Chilli", cat: "starter", price: 180 },
  { name: "Lassi", cat: "drink", price: 90 },
];
const byPrice = [...dishes].sort((a, b) => a.price - b.price);
console.log(byPrice.map((d) => d.name));
const byCatThenPriceDesc = [...dishes].sort((a, b) => a.cat.localeCompare(b.cat) || b.price - a.price);
console.log(byCatThenPriceDesc.map((d) => `${d.cat}:${d.name}`));

The rest of this lesson

  • How comparators workexplain
  • Why stability mattersexplain
  • Comparator resultpredict
  • Comparator for each ordermatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of Algorithms