Merge pull request #16 from paulsonjpaul/feature/bubble-js

Add bubble sort JavaScript version
pull/17/head
Ming Tsai 2021-01-20 11:42:30 -04:00 committed by GitHub
commit 625fd1770c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 0 deletions

View File

@ -10,4 +10,7 @@
1. [Bubble Sort](python/bubble-sort.py) 1. [Bubble Sort](python/bubble-sort.py)
### JavaScript
1. [Bubble Sort](js/bubble-sort.js)

View File

@ -0,0 +1,20 @@
// Bubble Sorting JavaScript Version
function bubbleSort(arr) {
// Copy the contents of the input array and store them as a separate variable
let sorted = [...arr];
// Loop through the copied array
for (let i = 0; i < sorted.length; i++) {
// Checks if an item in the array is greater than the item next to it (index + 1)
if (sorted[i] > sorted[i + 1]) {
// If yes, swap them
sorted.splice(i, 2, sorted[i + 1], sorted[i]);
}
}
// Finally return the sorted array
return sorted;
}
// Log to the console and have fun
console.log(bubbleSort([23, 34, 25, 12, 54, 11]));