Skip to content

Instantly share code, notes, and snippets.

@p8ul
Created October 1, 2019 17:50
Show Gist options
  • Save p8ul/2a1b8b42a83658ee6b1e210b10ea3afd to your computer and use it in GitHub Desktop.
Save p8ul/2a1b8b42a83658ee6b1e210b10ea3afd to your computer and use it in GitHub Desktop.
Bubble sort
// https://en.wikipedia.org/wiki/Bubble_sort
const sortList = (arrInput) => {
// Clone to prevent modification or original input array.
let arr = [...arrInput];
let len = arr.length;
// Boolean that determins whether the swap has occur or not.
let swapped;
do {
swapped = false;
for (let i = 0; i < len; i ++) {
// Swap elements if they are in wrong order
if (arr[i] > arr[i + 1] ) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true
}
}
} while (swapped)
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment