1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class myPriorityQueue{ constructor({compare = (a,b) => a-b}){ this.compare = compare; this.data = []; } swap(i, j){ [this.data[i], this.data[j]] = [this.data[j], this.data[i]]; } size(){ return this.data.length; } peak(){ if(this.size() === 0) return null; return this.data[0]; } push(value){ this.data.push(value); this.bubbleUp(this.data.length - 1); } // pop the highest priority item // use array shift will be O(n) // swap the first and last is O(1) pop(){ if(this.size() > 0){ const ans = this.data[0]; const last = this.data.pop(); if(this.size() > 0){ this.data[0] = last; this.bubbleDown(0); } return ans; } return null; } bubbleUp(index){ while(index > 0){ let parentIndex = Math.floor((index-1)/2); if(parentIndex >= 0 && this.compare(this.data[index], this.data[parentIndex]) < 0){ this.swap(index, parentIndex); index = parentIndex; }else{ break; } } } bubbleDown(index){ while(index < this.size()){ const leftChildIndex = index*2 + 1; const rightChildIndex = index*2 + 2; let smallestIndex = index; if(leftChildIndex < this.size() && this.compare(this.data[leftChildIndex], this.data[smallestIndex]) < 0){ smallestIndex = leftChildIndex; } if(rightChildIndex < this.size() && this.compare(this.data[rightChildIndex], this.data[smallestIndex]) < 0){ smallestIndex = rightChildIndex; } if(smallestIndex !== index){ this.swap(smallestIndex, index); index = smallestIndex; }else{ break; } } } }
|