Skip to content

Instantly share code, notes, and snippets.

@tlehman
Last active October 7, 2020 19:14
Show Gist options
  • Save tlehman/473e155bdd454e5b0494ba12e5afae95 to your computer and use it in GitHub Desktop.
Save tlehman/473e155bdd454e5b0494ba12e5afae95 to your computer and use it in GitHub Desktop.
const items = [4,8,0,3,1,5,7,2,6,9];
console.log(items);
quicksort<number>(items);
console.log(items);
export function quicksort<T>(items: T[]): void {
quicksortSub(items, 0, items.length-1);
}
function quicksortSub<T>(items: T[], lo: number, hi: number) {
if(lo < hi) {
const p = partition<T>(items, lo, hi);
quicksortSub(items, lo, p-1);
quicksortSub(items, p+1, hi)
}
}
function partition<T>(items: T[], lo: number, hi: number): number {
const pivot = items[hi];
let i = lo;
for(let j = lo; j < hi; j++) {
if(items[j] < pivot) {
[items[i], items[j]] = [items[j], items[i]];
i++;
}
}
[items[i], items[hi]] = [items[hi], items[i]];
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment