DEV Community

Discussion on: Bubble Sorting for Beginners in JS

Collapse
 
nosnastya profile image
Anastasiia • Edited

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.

Collapse
 
hansoncoding profile image
Hans • Edited

I just modified yours and was curious what would happen if I used ~500 random numbers, assigned to const and frozen... Using object.freeze alone makes a such a MASSIVE impact, I didn't realize...

// RESOURCES:
// 
// Video Describing Bubble Sort Process
//    https://www.youtube.com/watch?v=6Gv8vg0kcHc
// IIFE Stuff
//    https://flaviocopes.com/javascript-iife/
// Bubble Sorting Post & Discussion (Read Comments!)
//    https://dev.to/ryan_dunton/bubble-sorting-for-beginners-in-js-2opp 
// Destructuring
//    https://hackernoon.com/temporary-swap-vs-xor-swap-vs-destructuring-assignment-easy-swap-7e3f1f047db5


// generate random numbers (not concerned about performance here)
        var arr = [];
        for (var i = 0; i < 500; i++)
        {
            arr.push(Math.floor(Math.random() * 499) + 1)
        }
        console.log(arr);

/*
1. use const to avoid reassignment mutations and 
2. lock it dock further by freezing the object... (speeds it up 4x)
   Comment out object.freeze to see a massive drop in preformance...
3. TODO: Experiment with TypedArrays and fill method ?
*/
// const data = [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];
const data = arr;
Object.freeze(data);

// use a function expression to avoid hoisting & const to avoid global namespace of function name
const bubbleSort = (arr) => {
  // use map instead of loop to use temp values & avoid mutations of original data.
  arr.map(ary => {
    arr.map((num, i) => {
      // compare arr[i] (left) with arr[i + 1] (right)
      // if left is greater than right, swap them via destructuring
      if (arr[i] > arr[i + 1]) {
       [arr[i+1], arr[i] ] = [arr[i], arr[i+1]]; 
      }
    })
  })
  return arr;
};

/*
PERF TESTING: 
132 Originally... 
408 By freezing the array...
1. ; Prevents issues when blindly concatenating two JavaScript files
2. Wrapped code to avoid issues with global scop, for quicker experiment
*/
;((a)=> {
  /* */
  let operations = 0;
  const bubbleSort = (arr) => {
    arr.map(ary => {
      arr.map((num, i) => {
        if (arr[i] > arr[i + 1]) {
          [arr[i+1], arr[i] ] = [arr[i], arr[i+1]]; 
          operations++;
        }
      })
    })
    return arr;
  }
  bubbleSort(a)
  console.log('Operations: ' + operations)
})(data)