Skip to content

Bubble sort JavaScript

  • by

Bubble sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. In JavaScript, bubble sort can be implemented using a while loop and a nested for loop to compare adjacent elements and swap them if necessary.

The algorithm continues iterating through the array until no more swaps are needed, indicating that the array is sorted. Bubble sort has a time complexity of O(n^2), making it less efficient than other sorting algorithms like quicksort and mergesort.

Bubble sort JavaScript example

Simple example code implementation of the bubble sort algorithm in JavaScript:

<!DOCTYPE html>
<html>
  <body>    
    <script>
    function bubbleSort(array) {
    let isSorted = false;
    let lastUnsorted = array.length - 1;

    while (!isSorted) {
        isSorted = true;
        for (let i = 0; i < lastUnsorted; i++) {
            if (array[i] > array[i + 1]) {
                swap(array, i, i + 1);
                isSorted = false;
            }
        }
        lastUnsorted--;
    }
    return array;
    }

    function swap(array, i, j) {
        const temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    const unsortedArray = [5, 3, 8, 4, 2];
    const sortedArray = bubbleSort(unsortedArray);
    console.log(sortedArray); 

    </script>
  </body>
</html>

Output:

Bubble sort JavaScript
  1. Initialize a boolean variable isSorted to false and a variable lastUnsorted to the index of the last element in the array.
  2. While isSorted is false:
    • Set isSorted to true.
    • Iterate through the array from index 0 to lastUnsorted.
    • If the current element is greater than the next element, swap them and set isSorted to false.
    • Decrement lastUnsorted by 1.
  3. Return the sorted array.

Another code

function bubbleSort(array) {
  const arrayLength = array.length;

  for (let i = 0; i < arrayLength; i++) {
    let isSwapped = false;

    for (let j = 0; j < arrayLength - i - 1; j++) {
      if (array[j] > array[j + 1]) {
        swap(array, j, j + 1);
        isSwapped = true;
      }
    }

    if (!isSwapped) {
      // No swaps were made, array is already sorted
      break;
    }
  }

  return array;
}

function swap(array, i, j) {
  const temp = array[i];
  array[i] = array[j];
  array[j] = temp;
}

Comment if you have any doubts or suggestions on this JS sorting algorithm topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading