8 min read
🧩intermediate

Sorting Algorithms — Putting Things in Order

Learn how Bubble Sort, Selection Sort, and the built-in sort work — and why some are faster than others.

Why Sorting Matters

Sorting is one of the most fundamental operations in programming. Search engines sort results by relevance. Stores sort products by price. Leaderboards sort players by score. There are many ways to sort a list, and some are much faster than others. Understanding sorting algorithms teaches you how to think about efficiency.

Bubble Sort — The Simple One

javascript
// Bubble Sort: compare neighbors, swap if wrong order
// Repeat until no swaps needed
function bubbleSort(arr) {
  let n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        // Swap
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
}

console.log(bubbleSort([5, 3, 8, 1, 2]));
// [1, 2, 3, 5, 8]

Selection Sort — Find the Minimum

javascript
// Selection Sort: find the smallest, put it first
// Then find the next smallest, put it second, etc.
function selectionSort(arr) {
  let n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let minIndex = i;
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
  }
  return arr;
}

console.log(selectionSort([64, 25, 12, 22, 11]));
// [11, 12, 22, 25, 64]

Speed Comparison

How fast are these algorithms? We measure speed using "Big O" notation: • Bubble Sort: O(n²) — slow for big lists • Selection Sort: O(n²) — also slow • JavaScript's built-in .sort(): O(n log n) — much faster For a list of 1,000 items: • O(n²) = ~1,000,000 operations • O(n log n) = ~10,000 operations That's 100x faster! For real projects, always use the built-in .sort() — but understanding how sorting works makes you a better programmer.

The Easy Way (Built-in Sort)

javascript
// JavaScript built-in sort
let nums = [5, 3, 8, 1, 2];

// Sort numbers (ascending)
nums.sort((a, b) => a - b);
console.log(nums); // [1, 2, 3, 5, 8]

// Sort numbers (descending)
nums.sort((a, b) => b - a);
console.log(nums); // [8, 5, 3, 2, 1]

// Sort strings
let names = ["Charlie", "Alice", "Bob"];
names.sort();
console.log(names); // ["Alice", "Bob", "Charlie"]
Pro Tip

JavaScript's .sort() without a comparison function sorts alphabetically, not numerically! [10, 2, 30].sort() gives [10, 2, 30] (wrong). Always use .sort((a, b) => a - b) for numbers.

Try It Yourself

Implement Bubble Sort, then test it with: [38, 27, 43, 3, 9, 82, 10]. Count how many swaps it takes. Now try to improve it: if no swaps happen in a pass, the array is already sorted — you can stop early.

Ready to build?

Put what you learned into practice — pick a project and start coding.

Start Building Free