-
-
Save abenteuerzeit/df043564cc8872751f02859988c9fa44 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
const swap = require("./swap"); | |
const bubbleSort = (input) => { | |
let swapCount = 0; | |
let swapping = true; | |
while (swapping) { | |
swapping = false; | |
for (let i = 0; i < input.length - 1; i++) { | |
if (input[i] > input[i + 1]) { | |
swap(input, i, i + 1); | |
swapCount++; | |
swapping = true; | |
} | |
} | |
} | |
console.log(`Swapped ${swapCount} times`); | |
return input; | |
}; | |
const arr1 = [9, 8, 7, 6, 5, 4, 3, 2, 1]; | |
const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
bubbleSort(arr1); | |
bubbleSort(arr2); | |
module.exports = bubbleSort; |
Author
abenteuerzeit
commented
Aug 17, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment