結合 PHP 後端產生排序步驟、HTML 表格呈現、CSS 高亮動畫,能直觀展示冒泡排序每輪比較與交換,是演算法教學的優秀素材。
<?php
function bubbleSortFrames(array $arr): array {
$frames = [];
$frames[] = ['arr' => $arr, 'desc' => '初始陣列', 'highlight' => []];
$n = count($arr);
for ($i = $n - 1; $i > 0; $i--) {
for ($j = 0; $j < $i; $j++) {
$frames[] = ['arr' => $arr, 'desc' => "第 {$n-$i} 輪 比較索引 $j 和 " . ($j+1), 'highlight' => [$j, $j+1]];
if ($arr[$j] > $arr[$j+1]) {
[$arr[$j], $arr[$j+1]] = [$arr[$j+1], $arr[$j]];
$frames[] = ['arr' => $arr, 'desc' => "交換 $j 和 " . ($j+1), 'highlight' => [$j, $j+1]];
}
}
}
$frames[] = ['arr' => $arr, 'desc' => '排序完成', 'highlight' => []];
return $frames;
}
// 使用
$initial = [64, 34, 25, 12, 22, 11, 90];
$frames = bubbleSortFrames($initial);
// 輸出 JSON 供前端 JS 消費,或直接在 PHP 迴圈輸出 HTML
?>
<style>
.table { border-collapse: collapse; margin: 20px auto; font-family: monospace; }
.cell { width: 40px; height: 40px; border: 1px solid #ccc; text-align: center; line-height: 40px; transition: background 0.3s; }
.cell.compare { background: #ffe0b2; } /* 比較中 */
.cell.swap { background: #ffccbc; } /* 交換後 */
.desc { text-align: center; margin: 10px; font-weight: bold; color: #333; }
</style>
<div id="demo"></div>
<script>
// 簡單 JS 播放幀 (假設 frames 為 PHP json_encode 輸出的 JS 陣列)
const frames = <?= json_encode($frames) ?>;
let idx = 0;
function render() {
const f = frames[idx];
document.getElementById('demo').innerHTML = `
<div class="desc">${f.desc}</div>
<table class="table"><tr>
${f.arr.map((v, i) => `<td class="cell ${f.highlight.includes(i) ? (f.desc.includes('交換') ? 'swap' : 'compare') : ''}">${v}</td>`).join('')}
</tr></table>
`;
}
render();
setInterval(() => { idx = (idx + 1) % frames.length; render(); }, 800);
</script>
$i--)。視覺化讓抽象演算法具體化,加深理解並方便除錯。