Skip to content

Commit 4369c29

Browse files
authored
Fix kSmallest exponent bug; add test for bug (#38)
1 parent 1edfcf3 commit 4369c29

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

FastPriorityQueue.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ FastPriorityQueue.prototype.forEach = function(callback) {
287287
FastPriorityQueue.prototype.kSmallest = function(k) {
288288
if ((this.size == 0) || (k<=0)) return [];
289289
k = Math.min(this.size, k);
290-
const newSize = Math.min(this.size, (1 << (k - 1)) + 1);
290+
const newSize = Math.min(this.size, (2 ** (k - 1)) + 1);
291291
if (newSize < 2) { return [this.peek()] }
292292

293293
const fpq = new FastPriorityQueue(this.compare);

unit/basictests.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,4 +341,18 @@ describe('FastPriorityQueue', function() {
341341
if (x.poll() != item) throw 'bug';
342342
}
343343
});
344+
345+
it('should return k smallest with large k', function() {
346+
// ascending
347+
var x = new FastPriorityQueue(function(a, b) {
348+
return a < b;
349+
});
350+
const largeK = 64;
351+
const items = Array.from({ length: largeK }, (_, k) => k);
352+
items.forEach((item) => x.add(item));
353+
354+
items.forEach((_,i) => {
355+
if (JSON.stringify(x.kSmallest(i + 1)) !== JSON.stringify(items.slice(0, i+1))) throw 'bug';
356+
});
357+
});
344358
});

0 commit comments

Comments
 (0)