Last active
February 7, 2019 11:44
-
-
Save brainyfarm/dfb7cd80d0b312bb9eb203957e102444 to your computer and use it in GitHub Desktop.
Bubble Sort JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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