I'm learning Haskell, and there was quicksort implementation, so I thought that I could implement it in a similar way in JavaScript. The result:
const quicksort = ([x, ...xs], compareFn = (a, b) => a - b) => {
// If x is undefined, the array is empty
if (x === undefined) return [];
const smallerSorted = quicksort(xs.filter(a => compareFn(a, x) <= 0), compareFn);
const biggerSorted = quicksort(xs.filter(a => compareFn(a, x) > 0), compareFn);
return [...smallerSorted, x, ...biggerSorted];
};
// Example usage:
console.log(quicksort(
Array.from({ length: 10 }).map(_ => Math.floor(Math.random() * 100))
));
console.log(quicksort(
Array.from('a quick brown fox jumped over a lazy dog'),
(a, b) => a.charCodeAt(0) - b.charCodeAt(0)
).join(''));
.as-console-wrapper { max-height: 100% !important; }
I realize that calling filter()
twice might be inefficient, so I made an alternative version, using the _.partition()
function from Lodash:
const quicksort = ([x, ...xs], compareFn = (a, b) => a - b) => {
// If x is undefined, the array is empty
if (x === undefined) return [];
const [smallerSorted, biggerSorted] = _.partition(
xs,
a => compareFn(a, x) <= 0
).map(arr => quicksort(arr, compareFn));
return [...smallerSorted, x, ...biggerSorted];
};
myarr.forEach
,myarr.map
etc.. use regularwhile\do-while
orfor
loops instead \$\endgroup\$