Last active
April 10, 2020 08:43
-
-
Save leolanese/a96e57ba9201f649e6347a763cb5e1b6 to your computer and use it in GitHub Desktop.
Sorting algorithms JS: Bubble Sort Implementation
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
// | |
// Bubble Sort Implementation | |
// | |
function bubbleSort (unsortedArray) { | |
if (unsortedArray.length <= 1) { | |
return unsortedArray; | |
} | |
for (let i = 0; i < unsortedArray.length; i++) { | |
for (let j = 0; j < (unsortedArray.length - i - 1); j++) { | |
// Swap if the element is larger than the element right next to it | |
if (unsortedArray[j] > unsortedArray[j+1]) { | |
[unsortedArray[j], unsortedArray[j+1]] = [unsortedArray[j+1], unsortedArray[j]]; // ES6 Swap | |
} | |
} | |
} | |
return unsortedArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment