Skip to content

Instantly share code, notes, and snippets.

@brainyfarm
Last active February 7, 2019 11:44
Show Gist options
  • Save brainyfarm/dfb7cd80d0b312bb9eb203957e102444 to your computer and use it in GitHub Desktop.
Save brainyfarm/dfb7cd80d0b312bb9eb203957e102444 to your computer and use it in GitHub Desktop.
Bubble Sort JS
/**
* My JS Implementation of Bubble Sort.
*/
const bubbleSort = arr => {
let noSwaps;
/**
* Swap element in an arr for another
*/
const swap = (arr, index1, index2) => {
let first = arr[index1];
let second = arr[index2];
arr[index1] = second;
arr[index2] = first;
}
/**
* Go through the element looking through the current item to determine if it is greater than the next then, swap them
*/
// Reverse looping to prevent comparision with undefined
for(let i = arr.length; i > 0; i--) {
noSwaps = true;
for(let j = 0; j < i - 1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr, j, j+1);
noSwaps = false;
}
}
if (noSwaps) break;
}
return arr;
}
bubbleSort([82, 37, 45, 29, 8, 11]) // [ 8, 11, 29, 37, 45, 82 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment