Bubble sort

버블 정렬

A sorting algorithm that swaps adjacent values out of order. Each pass places the largest remaining value on the right.

···
html
<div class="demo"><div class="head"><strong>BUBBLE SORT</strong><span id="status">compare</span></div><div class="scene" id="bars"></div><div class="foot"><span>compare → swap → repeat</span><span>tap to step</span></div></div>
css
.demo{width:min(92vw,660px);height:min(86vh,310px);border:1px solid var(--line);border-radius:14px;background:var(--surface);padding:clamp(10px,2.5vmin,20px);display:flex;flex-direction:column;gap:clamp(6px,1.7vmin,12px);box-shadow:0 10px 35px rgba(0,0,0,.07);font:500 clamp(10px,2.8vmin,15px)/1.35 ui-monospace,SFMono-Regular,Consolas,monospace}
.head,.foot{display:flex;align-items:center;justify-content:space-between;gap:8px}.head strong{color:var(--accent);font-size:1.05em}.foot{color:var(--muted);font-size:.85em;min-height:1.4em}.scene{flex:1;min-height:0;position:relative;display:flex;align-items:center;justify-content:center;gap:clamp(5px,1.5vmin,12px)}.chip{border:1px solid var(--line);background:var(--bg);border-radius:7px;padding:.4em .6em;text-align:center}.on{border-color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 12%,var(--surface))!important;color:var(--accent)!important}.dim{opacity:.42}.arrow{color:var(--muted)}
.scene{align-items:end}.bar{width:clamp(18px,7%,48px);border-radius:5px 5px 0 0;background:var(--muted);color:var(--surface);display:flex;align-items:end;justify-content:center;padding-bottom:4px;transition:height .3s,background .3s}.bar.active{background:var(--accent)}.bar.done{background:var(--accent-3)}
js
let values=[6,2,5,1,4,3],i=0,end=values.length-1;const bars=document.getElementById("bars"),status=document.getElementById("status");function draw(){bars.replaceChildren(...values.map((v,n)=>{const el=document.createElement("div");el.className="bar"+(n===i||n===i+1?" active":"")+(n>end?" done":"");el.style.height=(20+v*11)+"%";el.textContent=v;return el}));}function advance(){if(end===0){values=[6,2,5,1,4,3];i=0;end=values.length-1;status.textContent="restart";draw();return}if(values[i]>values[i+1]){[values[i],values[i+1]]=[values[i+1],values[i]];status.textContent="swap"}else status.textContent="keep";i++;if(i>=end){i=0;end--}draw()}draw();const timer=setInterval(advance,700);document.querySelector(".demo").addEventListener("pointerdown",()=>{clearInterval(timer);advance()})

Bubble sort scans an array and compares adjacent values. It swaps an out-of-order pair, then repeats over the unsorted portion until all values are in place.

The demo compares and swaps real array values. Colored bars mark the current pair; values fixed on the right leave the search range. Its comparison count grows quickly with input size, so it is mainly useful for teaching rather than large datasets.

When to use

Use it to learn comparison and swapping. Prefer the language’s standard sort function in production.

Open as page ↗