tw twBlog
Home
code May 2, 2026 2 min read 2 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.

Despite its simplicity, bubble sort is rarely used in production because its average and worst-case time complexity is O(n┬▓). It is, however, an excellent teaching example because the logic is easy to follow step by step.

How It Works

Each full pass through the array “bubbles” the largest unsorted value to its correct position at the end. After n ΓêÆ 1 passes the array is fully sorted. An early-exit optimisation using a swapped flag lets the algorithm stop as soon as a pass completes with no swaps ΓÇö giving O(n) best-case performance on an already-sorted input.

bubbleSort.js
<br />
/**<br />
 * Sorts an array in ascending order using the Bubble Sort algorithm.<br />
 *<br />
 * Bubble Sort works by repeatedly stepping through the list, comparing<br />
 * adjacent elements, and swapping them if they are in the wrong order.<br />
 * This process repeats until the array is fully sorted.<br />
 *<br />
 * Time Complexity:<br />
 *   – Best:    O(n)   — already sorted (with early exit optimization)<br />
 *   – Average: O(n²)<br />
 *   – Worst:   O(n²)<br />
 *<br />
 * Space Complexity: O(1) — sorts in place<br />
 *<br />
 * @param {number[]} arr – The array of numbers to sort<br />
 * @returns {number[]} The sorted array (sorted in place)<br />
 */<br />
function bubbleSort(arr) {<br />
  const n = arr.length;</p>
<p>  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]) {<br />
        // Swap adjacent elements<br />
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];<br />
        swapped = true;<br />
      }<br />
    }</p>
<p>    // If no swaps occurred, the array is already sorted — exit early<br />
    if (!swapped) break;<br />
  }</p>
<p>  return arr;<br />
}<br />

Related Posts

Comments 0

Leave a comment

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

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