Created
June 12, 2017 18:38
-
-
Save BeKnowDo/3572b1a2e2df6949753cfb9d65592ca5 to your computer and use it in GitHub Desktop.
Bubble Sort
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
const BubbleSort = (values) => { | |
let originalValues = values.slice(), | |
length = originalValues.length - 1, | |
swapped; | |
do { | |
swapped = false; | |
values.forEach((item, index, values) => { | |
let currentItem = values[index], | |
nextItem = values[index + 1] ? values[index + 1] : null; | |
if(nextItem && currentItem > nextItem) { | |
values[index] = nextItem; | |
values[index + 1] = currentItem; | |
swapped = true; | |
} | |
}); | |
} | |
while(swapped); | |
return values; | |
} | |
console.clear(); | |
const test = BubbleSort([34, 203, 3, 746, 200, 984, 198, 764, 9]); | |
console.log(test); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment