버블 정렬

Bubble sort

이웃한 두 값을 비교해 순서가 틀리면 바꾸는 정렬입니다. 매 반복마다 가장 큰 값이 오른쪽에 자리 잡습니다.

···
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()})

버블 정렬은 배열을 왼쪽부터 훑으며 이웃한 값을 비교합니다. 앞의 값이 더 크면 둘을 교환하고, 배열 끝까지 간 뒤 아직 정렬되지 않은 부분을 다시 훑습니다.

데모는 실제 배열 값을 한 쌍씩 비교하고 교환합니다. 색이 바뀐 막대가 현재 비교 대상이며, 오른쪽에서 확정된 값은 다시 비교하지 않습니다. 입력이 늘면 비교 횟수가 빠르게 증가하므로 큰 데이터의 기본 정렬 방법으로는 적합하지 않습니다.

언제 쓰나

정렬의 비교·교환 과정을 처음 배울 때 적합합니다. 실제 서비스에서는 언어의 표준 정렬 함수를 우선 사용하세요.

페이지로 열기 ↗