Algorithms: Implement Bubble Sort

This commit is contained in:
Manish 2023-08-22 10:51:58 +10:00
parent 3e3dce5f4a
commit e693c0078c

22
Algorithms/bubbleSort.js Normal file
View File

@ -0,0 +1,22 @@
// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-bubble-sort
function bubbleSort(array) {
// Only change code below this line
function swap(array, indexA, indexB) {
const tmp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = tmp;
}
let swaps = false;
do {
swaps = false;
for (let i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
swaps = true;
swap(array, i, i + 1);
}
}
} while (swaps);
return array;
// Only change code above this line
}