Last active
April 12, 2019 17:31
-
-
Save jviide/2d5883567f0b25d8492471581d713f91 to your computer and use it in GitHub Desktop.
Using a heap to sort by __depth
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
function push(array, item) { | |
let index = array.length; | |
while (index > 0) { | |
const parentIndex = ((index - 1) / 2) | 0; | |
if (array[parentIndex].__depth <= item.__depth) { | |
break; | |
} | |
array[index] = array[parentIndex]; | |
index = parentIndex; | |
} | |
array[index] = item; | |
} | |
function pop(array) { | |
const lastItem = array.pop(); | |
if (array.length === 0) { | |
return lastItem; | |
} | |
const item = array[0]; | |
array[0] = lastItem; | |
let index = 0; | |
for (;;) { | |
let smallest = index; | |
for (let i = index * 2 + 1, j = i + 2; i < j && i < array.length; i++) { | |
if (array[smallest].__depth > array[i].__depth) { | |
smallest = i; | |
} | |
} | |
if (index === smallest) { | |
break; | |
} | |
array[index] = array[smallest]; | |
index = smallest; | |
} | |
array[index] = lastItem; | |
return item; | |
} | |
const heap = []; | |
push(heap, { text: "give", __depth: 3 }); | |
push(heap, { text: "I'm", __depth: 0 }); | |
push(heap, { text: "you", __depth: 4 }); | |
push(heap, { text: "never", __depth: 1 }); | |
push(heap, { text: "up", __depth: 5 }); | |
push(heap, { text: "gonna", __depth: 2 }); | |
let item; | |
while ((item = pop(heap))) { | |
console.log(item.text); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment