
Security News
Meet Socket at Black Hat and DEF CON 2025 in Las Vegas
Meet Socket at Black Hat & DEF CON 2025 for 1:1s, insider security talks at Allegiant Stadium, and a private dinner with top minds in software supply chain security.
This is a simple min heap implementation.
Using npm
npm install minheap
Instantiate a heap using the compare function. If compare function is not given it falls back to a simple number comparison.
Required compare function should be similar to the function passed into Array.sort()
Pushes the value to the heap
Returns the value on top of the heap. This is the min value. If max value is required the compare function need to be altered accordingly.
Removes the top element from the heap and returns that value.
Following example finds the Kth smallest number of a number list in O(NlogK) time. This is efficient compared to sorting entire list which takes O(NlogN) time, given that K << N.
var Heap = require('minheap');
// Max heap
var heap = new Heap(function(a,b) {
return b - a;
});
var N = 1<<20;
var MAX_VAL = 1<<29;
var K = 10
var arr = [];
// Generate random list
for (var i=0; i<N; ++i) {
arr[i] = Math.floor(Math.random() * MAX_VAL);
}
// Finding Kth smallest in O(N log K) using the heap
for (var i=0; i<N; ++i) {
if (i < K) {
heap.push(arr[i]);
} else {
if (arr[i] < heap.top()) {
heap.pop();
heap.push(arr[i]);
}
}
}
console.log("10th smallest using heap: " + heap.top());
// Finding Kth smallest in O(N log N) by sorting the entire list
arr.sort(function(a,b) {
return a - b;
});
console.log("10th smallest using sort: " + arr[K-1]);
FAQs
Simple implementation of min-heap
The npm package minheap receives a total of 9 weekly downloads. As such, minheap popularity was classified as not popular.
We found that minheap demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Meet Socket at Black Hat & DEF CON 2025 for 1:1s, insider security talks at Allegiant Stadium, and a private dinner with top minds in software supply chain security.
Security News
CAI is a new open source AI framework that automates penetration testing tasks like scanning and exploitation up to 3,600× faster than humans.
Security News
Deno 2.4 brings back bundling, improves dependency updates and telemetry, and makes the runtime more practical for real-world JavaScript projects.