Skip to content

Instantly share code, notes, and snippets.

@leolanese
Last active April 10, 2020 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leolanese/a96e57ba9201f649e6347a763cb5e1b6 to your computer and use it in GitHub Desktop.
Save leolanese/a96e57ba9201f649e6347a763cb5e1b6 to your computer and use it in GitHub Desktop.
Sorting algorithms JS: Bubble Sort Implementation
//
// 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