Skip to content

Instantly share code, notes, and snippets.

@abenteuerzeit
Forked from codecademydev/bubbleSort.js
Created August 17, 2023 12:45
Show Gist options
  • Save abenteuerzeit/df043564cc8872751f02859988c9fa44 to your computer and use it in GitHub Desktop.
Save abenteuerzeit/df043564cc8872751f02859988c9fa44 to your computer and use it in GitHub Desktop.
Bubble sort
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;
@abenteuerzeit
Copy link
Author

const swap = (arr, indexOne, indexTwo) => {
  const temp = arr[indexTwo];
  arr[indexTwo] = arr[indexOne];
  arr[indexOne] = temp;
};

module.exports = swap;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment