Bubble Sort Algorithm in JavaScript

In this blog, we’re going to discuss sorting algorithm and learn about one of the simplest ones – the Bubble Sort algorithm. We’ll be implementing it in JavaScript, so if you’re a JavaScript enthusiast or just looking to brush up on your sorting algorithm knowledge, you’re in the right place. Keep reading to learn.

So, what is Bubble Sort? Bubble Sort is a straightforward sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. It’s not the most efficient algorithm for large datasets, but it’s a great starting point to understand sorting concepts.

bubble sort algo
Image from wikipedia
https://en.wikipedia.org/wiki/Bubble_sort

simple implementation of Bubble Sort in JavaScript:

function bubbleSort(arr) {
  const n = arr.length;

  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - 1 - i; j++) {
      // Compare adjacent elements
      if (arr[j] > arr[j + 1]) {
        // Swap them if they are in the wrong order
        const temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  return arr;
}

// Example usage:
const unsortedArray = [3, 30, 21, 14, 7, 0, 89];
const sortedArray = bubbleSort(unsortedArray.slice()); // Create a copy to keep the original array unchanged

console.log("Unsorted Array:", unsortedArray); //Unsorted Array: [3, 30, 21, 14, 7,  0, 89]
console.log("Sorted Array:", sortedArray); //Sorted Array: [0, 3, 7, 14, 21, 30, 89]

The function bubbleSort takes an array as an argument and performs the Bubble Sort algorithm on it. The outer loop iterates through the array, and the inner loop compares adjacent elements, swapping them if necessary.

You need to be logged in to view the rest of the content. Please . Not a Member? Join Us

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top