Created
October 1, 2019 17:50
-
-
Save p8ul/2a1b8b42a83658ee6b1e210b10ea3afd to your computer and use it in GitHub Desktop.
Bubble sort
This file contains 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
// 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