Skip to content

Instantly share code, notes, and snippets.

@cozzbie
Created January 9, 2020 09:30
Show Gist options
  • Save cozzbie/0c6b85b228a0c83f843b05bf8051d00e to your computer and use it in GitHub Desktop.
Save cozzbie/0c6b85b228a0c83f843b05bf8051d00e to your computer and use it in GitHub Desktop.
const swap = (array, a, b) => {
let tempa = array[a];
array[a] = array[b];
array[b] = tempa;
}
const maxheap = (array, index) => {
const parenty = i => Math.ceil(i/2);
const lefty = i => 2*i;
const righty = i => 2*i + 1;
const left = array[lefty(index)];
const right = array[righty(index)];
let largest = index;
if(lefty(index) < array.length && array[index] < left) {
largest = lefty(index);
} else if(righty(index) < array.length && array[index] < right) {
largest = righty(index);
}
if(largest !== index) {
swap(array, largest, index);
maxheap(array, largest);
}
}
const treeify = array => {
const len = Math.floor(array.length / 2) - 1;
for(let i = len; i >= 0; i--){
maxheap(array, i);
}
return array;
};
const heapsort = (array, sorted) => {
const heaped = treeify(array);
if(!array.length){
return sorted;
}
sorted.unshift(array.shift());
return heapsort(array, sorted);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment