Skip to content

Instantly share code, notes, and snippets.

@RyanHirsch
Last active March 14, 2019 13:13
Show Gist options
  • Save RyanHirsch/2a736e6c8152d3c685bf2009e4b2dc02 to your computer and use it in GitHub Desktop.
Save RyanHirsch/2a736e6c8152d3c685bf2009e4b2dc02 to your computer and use it in GitHub Desktop.
quicksort
const arr = [ 100, 1,3,4,6,0,8,11, 2,30,5];
function sort<T>(items: T[]) {
const copy = [...items];
quickSort(copy);
return copy;
}
function quickSort<T>(items: T[], start: number = 0, end:number = items.length) {
const length = end - start;
if(length <= 1) {
return;
}
const selectedPivotIndex = start + Math.floor(Math.random() * length);
swap(items, start, selectedPivotIndex);
const selectedPivotValue = items[start];
let partitionIndex = start;
for(let i = start + 1; i < end; i++) {
if(items[i] < selectedPivotValue) {
partitionIndex++;
swap(items, i, partitionIndex);
}
}
if(partitionIndex !== start) {
swap(items, start, partitionIndex);
}
quickSort(items, start, partitionIndex);
quickSort(items, partitionIndex + 1, end);
}
function filteredQuicksort<T>(items: T[]) {
if(items.length <= 1) {
return items;
}
const pivot = items[items.length - 1];
return [
...filteredQuicksort(items.filter(lessThan(item => item < pivot))),
pivot,
...filteredQuicksort(items.filter(greaterThan(item => item > pivot)))
]
}
function lessThan<T>(filterFn: (item: T) => boolean) {
return (item: T, idx: number, items: T[]) => filterFn(item) && idx < items.length - 1;
}
function greaterThan<T>(filterFn: (item: T)=> boolean) {
return (item: T, idx: number, items: T[]) => filterFn(item) && idx < items.length - 1;
}
function swap<T>(items: T[], a: number, b: number) {
[items[a], items[b]] = [items[b], items[a]];
}
console.log(sort(arr));
console.log(filteredQuicksort(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment