Skip to content

Commit

Permalink
Optimize baseline and special case performance for kSmallest (#37)
Browse files Browse the repository at this point in the history
* Optimize baseline and special case performance for kSmallest

* PR feedback: check k earlier, simplify conditional
  • Loading branch information
Barbarrosa authored Mar 3, 2023
1 parent 7b70143 commit c571bcf
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions FastPriorityQueue.js
Original file line number Diff line number Diff line change
Expand Up @@ -285,15 +285,17 @@ FastPriorityQueue.prototype.forEach = function(callback) {
// runs in O(k log k) time, the elements are not removed
// from the priority queue.
FastPriorityQueue.prototype.kSmallest = function(k) {
if (this.size == 0) return [];
if ((this.size == 0) || (k<=0)) return [];
k = Math.min(this.size, k);
var fpq = new FastPriorityQueue(this.compare);
const newSize = Math.min((k > 0 ? Math.pow(2, k - 1) : 0) + 1, this.size);
const newSize = Math.min(this.size, (1 << (k - 1)) + 1);
if (newSize < 2) { return [this.peek()] }

const fpq = new FastPriorityQueue(this.compare);
fpq.size = newSize;
fpq.array = this.array.slice(0, newSize);

var smallest = new Array(k);
for (var i = 0; i < k; i++) {
const smallest = new Array(k);
for (let i = 0; i < k; i++) {
smallest[i] = fpq.poll();
}
return smallest;
Expand Down

0 comments on commit c571bcf

Please sign in to comment.