algopat
Version:
Utility library for implementing common design patterns and algorithms
31 lines • 1.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.selectionSort = void 0;
/**
* Performs an in-place selection sort on the given array.
* @param arr The array to sort.
* @param compareFn The function to compare two elements.
* @param options The options for the selection sort.
* @returns The sorted array (same reference as input).
*/
const selectionSort = (arr, compareFn = (a, b) => (a < b ? -1 : a > b ? 1 : 0), options) => {
const defaultOptions = {
mutable: true,
...options,
};
const output = defaultOptions?.mutable ? arr : [...arr];
for (let i = 0; i < output.length - 1; i++) {
const key = arr[i];
let minIndex = i;
for (let j = i + 1; j < output.length; j++) {
if (compareFn(output[j], output[minIndex]) < 0) {
minIndex = j;
}
}
output[i] = output[minIndex];
output[minIndex] = key;
}
return output;
};
exports.selectionSort = selectionSort;
//# sourceMappingURL=select-sort.algorithm.js.map