Bubble Sorting for Beginners in JS

Ryan Dunton on January 15, 2019

As someone who uses Javascript all day, every day for work I realized I took a lot of basic algorithm tasks for granted so I have decided to dive... [Read Full]
markdown guide
 

In some cases the best solution is the one use less operations to perform any task, some of them takes the memory usage, anyhow at least for this one you have to check the operations you are performing to solve this one.

I found something weird, is a bit complex to mentally process at first glance, anyhow it takes more steps that it should.

First:

(function (a) {
/*Wrapped code to avoid issues with global scop, for quicker experiment*/
let operations = 0; 
const bubbleSort = arr => {
  let swapped;
  do {
    swapped = false;
    /* The length is calculated each iteration and most important, you iterate over the entire array multiple times */
    for (let i = 0; i < arr.length; i++, operations++) {
      if (arr[i] > arr[i + 1]) {
        let tmp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = tmp;
        swapped = true;
      }
    }
  } while (swapped);
  console.log('Operations:', operations) // Operations: 884
  return arr;
};
bubbleSort(a) 
})([1,2,6,9,4,1,2,3,5,67,8,9,2,23,5,67,7,678,2,12,34,546,567,678,890,678,34,3453,123,345,46,57,678,4])

You can create an "optimized solution cutting of some iterations"

(function(a) {
   /*wrapping to avoid global scope*/
   let operations = 0;
   const bubbleSort = (arr) => {
     /* allocating size one time and cutting some iterations starting a second loop on the n+1 array*/
     for(let i = 0, size = arr.length; i < size; i++) {
        for(let e = i+1; e < size; e++, operations++) {
            if (arr[i] > arr[e]) [arr[i], arr[e]] = [arr[e], arr[i]]
        }  
     }
     return arr
   }
   bubbleSort(a)
   console.log('Operations', operations) //Operations 561 
   /*wrapping to avoid global scope*/
})([1,2,6,9,4,1,2,3,5,67,8,9,2,23,5,67,7,678,2,12,34,546,567,678,890,678,34,3453,123,345,46,57,678,4])

This is just an experimental case, but in some cases it can crash the app or being unable to perform a task ;)

 
 

I was trying to figure out how to efficiently implement different kinds of sorting algorithms in ES6 style and that's what I've came up with for bubble algorithm:

Basically, it's the same as yours, but it uses .map() method instead of for loop and destructuring to swap elements. It also uses 132 Operations, if testing like Marco showed here.

code of conduct - report abuse