lgrthms
Version:
Algorithms and data structures for your JavaScript and TypeScript projects 🧑💻
24 lines (23 loc) • 753 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.bubbleSort = void 0;
const Comparator_1 = require("../../utils/Comparator");
const arrays_1 = require("../../utils/arrays");
// O(n^2) time | O(1) space
function bubbleSort(array, compareFn) {
const comparator = new Comparator_1.Comparator(compareFn);
let isSorted = false;
let lastIdx = array.length - 1;
while (!isSorted) {
isSorted = true;
for (let i = 0; i < lastIdx; i++) {
if (comparator.isGreaterThan(array[i], array[i + 1])) {
(0, arrays_1.swap)(array, i, i + 1);
isSorted = false;
}
}
lastIdx--;
}
return array;
}
exports.bubbleSort = bubbleSort;