Heap priority queue

힙 우선순위 큐

Keep the highest-priority value at the root and bubble new values upward.

···
html
<div class="v"><header><b>MAX HEAP</b><span id="state"></span></header><main><div class="tree" id="tree"></div><div class="insert">insert <b>9</b> ↑</div></main><footer>parent ≥ children</footer></div>
css
.v{width:min(92vw,660px);height:min(86vh,310px);box-sizing:border-box;padding:clamp(9px,2.5vmin,18px);border:1px solid var(--line);border-radius:14px;background:var(--surface);display:flex;flex-direction:column;gap:7px;color:var(--fg);font:500 clamp(15px,4.5vmin,19px)/1.25 var(--font-sans, sans-serif)}.v header,.v footer{display:flex;justify-content:space-between;align-items:center;gap:8px;white-space:nowrap}.v header b{color:var(--accent);font-size:.9em}.v header span,.v footer{color:var(--muted);font-size:.82em}.v main{flex:1;min-height:0;position:relative;overflow:hidden}.v .mono{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.v .active{background:var(--accent)!important;color:var(--bg)!important;border-color:var(--accent)!important}.v .muted{opacity:.45} .tree{height:70%;display:grid;grid-template-columns:repeat(4,1fr);grid-template-rows:repeat(3,1fr);place-items:center}.node{width:28px;height:28px;border:1px solid var(--line);border-radius:50%;display:grid;place-items:center;font:700 .9em ui-monospace,monospace}.node:nth-child(1){grid-column:2/4}.node:nth-child(2){grid-column:1/3}.node:nth-child(3){grid-column:3/5}.node:nth-child(4){grid-column:1}.node:nth-child(5){grid-column:2}.node:nth-child(6){grid-column:3}.node:nth-child(7){grid-column:4}.insert{text-align:center;color:var(--muted)}.insert b{color:var(--accent)}
js
const steps=[[8,6,7,2,4,5,9],[8,6,9,2,4,5,7],[9,6,8,2,4,5,7]];let s=0;function draw(){document.getElementById("tree").innerHTML=steps[s].map((v,i)=>"<div class=\"node "+(v===9?"active":"")+"\">"+v+"</div>").join("");document.getElementById("state").textContent=["append","swap parent","root restored"][s];s=(s+1)%3}draw();setInterval(draw,1050)

A max heap is a complete binary tree whose parent is never smaller than its children. Insert at the end and swap upward until the invariant holds.

The maximum sits at the root; insert and removal follow the tree height. The full array is not sorted, so arbitrary ranks are not directly available.

When to use

Use it when repeatedly taking the next priority item, such as scheduling or path search.

Open as page ↗