Skip to content

Instantly share code, notes, and snippets.

@shanehh
Created August 3, 2020 06:19
Show Gist options
  • Save shanehh/c00f0f5dfbe37e946a970ec85e6865e1 to your computer and use it in GitHub Desktop.
Save shanehh/c00f0f5dfbe37e946a970ec85e6865e1 to your computer and use it in GitHub Desktop.
ES6 bubblesort
const bubbleSort = arr => {
if (!Array.isArray(arr)) {
return -1
}
if (arr.length < 2) {
return arr
}
for (let n = 0; n < arr.length; n++) {
let swapped = false
// no need to compare the last n element, it's already biggest ordered.
// -1 means that only needs to traverse to the second to last, and compare the second to last and the last.
for (let i = 0; i < arr.length - n - 1; i++) {
if (arr[i] > arr[i + 1]) {
// es6 style swap
;[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]
swapped = true
}
}
// if no swapping happen, the arr is already ordered.
if (!swapped) {
break
}
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment