 # WTF is Bubble Sort ?

Bubble sort is a type of sorting algorithm. Its not the best for everything but it does have its uses. It gets its name since it makes the largest values “bubble” to the top. Bubble sort does its job by using pair comparisons. So it takes the current value and compares it to it’s neighbor directly to the right.

Below you can see what I mean. We first take 5 and compare it 3, then ask the question “is 5 greater then 3 ? ” Then if it is, 5 switches places with 3 and if it isn’t then they stay in the same place, and move on to the next value. Here you can see a non optimized implementation of it:

 // Note this is without any optimizations const bubblesort = (arr) => { // We have a loop here to slowly shrink how much of the array we cover // So that we don't constantly keep looping over the whole array for(let i = arr.length; i > 0; i—){ // This loop, covers the length of the array given to us by the // loop above. for(let j = 0; j < i – 1; i ++){ // Here we do the comparison that asks the question // "does the value I am currently at greater then its neighbor ?" // if it is, then we switch the values around, if it isn't we do nothing if(arr[j] > arr[j+1]){ let tempVal = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tempVal; } } } }

view raw
BubbleSort.js
hosted with ❤ by GitHub