This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var PriorityQueue = function() { | |
this.heap = new Array(); //二分木の配列表現 | |
this.pointer = 0; //最終ノードを表すポインタ | |
}; | |
PriorityQueue.prototype = { | |
push : function(x) { | |
var i = this.pointer++; | |
while (i > 0) { | |
//親ノードの番号を求める | |
var p = Math.floor((i - 1) / 2); | |
//もう逆転してなければ処理を打ち切る | |
if (this.heap[p] <= x) break; | |
this.heap[i] = this.heap[p]; | |
i = p; | |
} | |
this.heap[i] = x; | |
}, | |
pop : function() { | |
var ret = this.heap[0]; | |
var x = this.heap[--this.pointer]; | |
var i = 0; | |
//子ノードがなくなるまでループ | |
while (i * 2 + 1 < this.pointer) { | |
var a = i * 2 + 1; //左子ノード | |
var b = i * 2 + 2; //右子ノード | |
if (b < this.pointer && this.heap[b] < this.heap[a]) a = b; | |
//もう逆転してなければ処理を打ち切る | |
if (this.heap[a] >= x) break; | |
this.heap[i] = this.heap[a]; | |
i = a; | |
} | |
this.heap[i] = x; | |
//最終ノードを削除する | |
this.heap.pop(); | |
return ret; | |
}, | |
size : function() { | |
return this.heap.length; | |
} | |
}; | |
function test() { | |
//テストコード | |
var queue = new PriorityQueue(); | |
queue.push(5); | |
queue.push(3); | |
queue.push(4); | |
queue.push(1); | |
queue.push(2); | |
alert(queue.size()); // => 5 | |
alert(queue.pop()); // => 1 | |
alert(queue.pop()); // => 2 | |
alert(queue.pop()); // => 3 | |
alert(queue.size()); // => 2 | |
queue.push(6); | |
alert(queue.size()); // => 3 | |
alert(queue.pop()); // => 4 | |
queue.push(2); | |
alert(queue.pop()); // => 2 | |
} | |
でも書き終わった後にJavaScriptのArrayにはsortメソッドがあることを思い出した。
pushもpopもあるからプライオリティーキューなんかいらんがな。