DEV Community

Discussion on: Bubble Sorting for Beginners in JS

Collapse
 
mdor profile image
Marco Antonio Dominguez

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 ;)

Collapse
 
ryan_dunton profile image
Ryan Dunton

thanks!