Skip to content

Instantly share code, notes, and snippets.

@lykkin
Created February 7, 2017 07:11
Show Gist options
  • Save lykkin/935a3a242b1a5f6bd050fae8742cda15 to your computer and use it in GitHub Desktop.
Save lykkin/935a3a242b1a5f6bd050fae8742cda15 to your computer and use it in GitHub Desktop.
heapin it on
var heap = {
heap: [],
add(n) {
this.heap.push(n)
this.siftUp()
},
pop() {
let res = this.heap[0]
this.heap[0] = this.heap[this.heap.length - 1]
this.heap.pop()
this.siftDown()
return res
},
siftDown() {
let curr = 0
let top = this.heap[curr]
let leftIdx = curr * 2 + 1
let rightIdx = leftIdx + 1
while (leftIdx < this.heap.length) {
if (rightIdx < this.heap.length) {
if (this.heap[leftIdx] < this.heap[rightIdx]) {
if (this.heap[leftIdx] < this.heap[curr]) {
this.heap[curr] = this.heap[leftIdx]
this.heap[leftIdx] = top
curr = leftIdx
} else {
break
}
} else {
if (this.heap[rightIdx] < this.heap[curr]) {
this.heap[curr] = this.heap[rightIdx]
this.heap[rightIdx] = top
curr = rightIdx
} else {
break
}
}
} else {
if (this.heap[leftIdx] < this.heap[curr]) {
this.heap[curr] = this.heap[leftIdx]
this.heap[leftIdx] = top
curr = leftIdx
} else {
break
}
}
leftIdx = curr * 2 + 1
rightIdx = leftIdx + 1
}
},
siftUp() {
let curr = this.heap.length - 1
let bot = this.heap[curr]
let next = Math.ceil((curr - 2) / 2)
while (next >= 0 && this.heap[next] > this.heap[curr]) {
this.heap[curr] = this.heap[next]
this.heap[next] = bot
curr = next
next = Math.ceil((curr - 2) / 2)
}
}
}
for (var i = 0; i < 100; i++) {
heap.add(Math.ceil(Math.random() * 100))
}
while(heap.heap.length) {
console.log(heap.pop())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment