Created
February 9, 2017 10:21
-
-
Save w8r/154fdd66b394e3c9a09f23864ab90369 to your computer and use it in GitHub Desktop.
min heap
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 minHeap (cmp, arr = []) { | |
const up = (i) => { | |
let object = arr[i]; | |
while (i > 0) { | |
let up = ((i + 1) >> 1) - 1, | |
parent = arr[up]; | |
if (cmp(object, parent) >= 0) break; | |
arr[parent.index = i] = parent; | |
arr[object.index = i = up] = object; | |
} | |
}; | |
const down = (i) => { | |
let object = arr[i]; | |
while (true) { | |
let right = (i + 1) << 1, | |
left = right - 1, | |
down = i, | |
child = arr[down], | |
len = arr.length; | |
if (left < len && cmp(arr[left], child) < 0) child = arr[down = left]; | |
if (right < len && cmp(arr[right], child) < 0) child = arr[down = right]; | |
if (down === i) break; | |
arr[child.index = i] = child; | |
arr[object.index = i = down] = object; | |
} | |
}; | |
return { | |
push (...args) { | |
for (let i = 0, n = args.length; i < n; ++i) { | |
let object = arguments[i]; | |
up(object.index = arr.push(object) - 1); | |
} | |
return arr.length; | |
}, | |
pop () { | |
const removed = arr[0]; | |
let object = arr.pop(); | |
if (arr.length) { | |
arr[object.index = 0] = object; | |
down(0); | |
} | |
return removed; | |
}, | |
remove (removed) { | |
const i = removed.index; | |
let object = arr.pop(); | |
if (i !== arr.length) { | |
arr[object.index = i] = object; | |
(cmp(object, removed) < 0 ? up : down)(i); | |
} | |
return i; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment