const arr = [1, 200, 49, 32, 78, 100];
const a = value => value < pivot;
const quickSort = (arr) => {
if (arr.length < 2) {
return arr;
} else {
const pivot = arr[Math.floor(Math.random() * arr.length)];
const less = arr.filter(value => value < pivot);
const greater = arr.filter(value => value > pivot);
return [...quickSort(less), pivot, ...quickSort(greater)];
}
}
function quickSort(arr, a или b)
, где "а" сортирует массив как [1, 2, 3]
, а "b" сортирует массив как [3, 2, 1]
. const defaultOrder = (a, b) => a < b ? -1 : a > b ? 1 : 0
const qSort = (arr, order = defaultOrder) => {
if (arr.length < 2) {
return arr;
}
const pivot = arr[Math.floor(arr.length * Math.random())]
const less = arr.filter(a => order(a, pivot) < 0)
const equal = arr.filter(a => order(a, pivot) === 0)
const greater = arr.filter(a => order(a, pivot) > 0)
return qSort(less, order).concat(equal).concat(qSort(greater, order))
}
function qSort(array, comparator, divider) {
if (array.length < 2) {
return array;
}
const defaultComparator = (a, b) => ((a < b) ? -1 : ((a > b) ? 1 : 0));
const defaultDivider = array => array[Math.floor(array.length * Math.random())];
const getOrder = comparator || defaultComparator;
const getPivot = divider || defaultDivider;
const pivot = getPivot(array);
const less = [], equal = [], greater = [];
for (const item of array) {
const order = getOrder(item, pivot);
const subArray = ((order < 0) ? less : ((order > 0) ? greater : equal));
subArray.push(item);
}
return [...qSort(less, getOrder, getPivot), ...equal, ...qSort(greater, getOrder, getPivot)];
}