tw twBlog
Home
code May 2, 2026 1 min read 15 views

source code test

chris

chris

chris

Share

Bubble Sort in JavaScript

Bubble sort is one of the simplest sorting algorithms. It works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which means the list is sorted.

How It Works

bubbleSort.js

/**
 * Sorts an array in ascending order using the Bubble Sort algorithm.
 *
 * Bubble Sort works by repeatedly stepping through the list, comparing
 * adjacent elements, and swapping them if they are in the wrong order.
 * This process repeats until the array is fully sorted.
 *
 * Time Complexity:
 *   - Best:    O(n)   — already sorted (with early exit optimization)
 *   - Average: O(n²)
 *   - Worst:   O(n²)
 *
 * Space Complexity: O(1) — sorts in place
 *
 * @param {number[]} arr - The array of numbers to sort
 * @returns {number[]} The sorted array (sorted in place)
 */
function bubbleSort(arr) {
  const n = arr.length;

  for (let i = 0; i < n - 1; i++) {
    let swapped = false;

    // Each pass bubbles the largest unsorted element to the end,
    // so we can shrink the inner loop by i each time.
    for (let j = 0; j < n - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        // Swap adjacent elements
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapped = true;
      }
    }

    // If no swaps occurred, the array is already sorted — exit early
    if (!swapped) break;
  }

  return arr;
}

Related Posts

Comments 0

Leave a comment

Your email will not be published. Sign in for a faster experience.

Supports **bold**, *italic*, and `code`.