- For each element index
ifrom the end of the array to the beginning - For each element index
jfrom the beginning to i - 1 - If
arr[j]is greater thanarr[j + 1], swap those two values - Return the sorted array
Javascript Implementation
function bubbleSort(arr, fn) {
const comparator = typeof fn === "function" ? fn : (x, y) => x - y;
for (let i = arr.length; i > 0; i--) {
for (let j = 0; j < i - 1; j++) {
if (comparator(arr[j], arr[j + 1]) > 0) swap(arr, j, j + 1);
}
}
return arr;
}
function swap(arr, i1, i2) {
[arr[i2], arr[i1]] = [arr[i1], arr[i2]];
}