re: Bubble Sorting for Beginners in JS VIEW POST


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.


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

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
   console.log('Operations', operations) //Operations 561 
   /*wrapping to avoid global scope*/

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

code of conduct - report abuse