freeCodeCamp/Algorithms/bubbleSort.js

23 lines
572 B
JavaScript
Raw Normal View History

2023-08-22 02:51:58 +02:00
// 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
}