Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
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 2 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
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.