Last active
October 7, 2020 19:14
-
-
Save tlehman/473e155bdd454e5b0494ba12e5afae95 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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