Prompt specification
Build or customize the Three.js 3D scene "Insertion and merge sorting comparison" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Insertion and merge sorting comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/insertion-and-merge-sorting-comparison-x1906
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a stylized solid sorting comparison. Put the same small list of numbered blocks on two parallel shelves, using repeated values with unique identity marks. Run insertion sort on one shelf and merge sort on the other, with step controls and clearly visible temporary storage for merging. Count comparisons and data moves separately under one published convention, including whether writes to temporary storage count as moves. Both sides must preserve the original block collection and end in sorted order. Allow different amounts of work per visual step, so animation speed is not presented as a measurement of algorithmic complexity.
Working Three.js Starter (insertion-and-merge-sorting-comparison-x1906):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Solid Sorting Comparison — Insertion vs Merge</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: #101d2f;
--panel-2: #15263d;
--border: #29415f;
--text: #e8f1ff;
--muted: #9cb0ca;
--cyan: #5ee7ff;
--orange: #ffb86b;
--green: #71e6a8;
--pink: #ff84bd;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
color: var(--text);
background:
radial-gradient(circle at 12% 0%, #17304b 0, transparent 33rem),
radial-gradient(circle at 92% 10%, #281b42 0, transparent 30rem),
var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: var(--text);
background: #1a2d46;
border: 1px solid #365372;
border-radius: 9px;
padding: 0.65rem 0.9rem;
cursor: pointer;
transition:
background 120ms ease,
border-color 120ms ease,
transform 120ms ease;
}
button:hover:not(:disabled) {
background: #243d5d;
border-color: #5a7899;
transform: translateY(-1px);
}
button:disabled {
opacity: 0.38;
cursor: not-allowed;
}
button.primary {
color: #07111c;
background: var(--cyan);
border-color: var(--cyan);
font-weight: 750;
}
button.primary:hover:not(:disabled) {
background: #9af0ff;
}
.app {
width: min(1500px, calc(100% - 28px));
margin: 0 auto;
padding: 26px 0 40px;
}
header {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 24px;
align-items: start;
margin-bottom: 18px;
}
.eyebrow {
color: var(--cyan);
font-size: 0.76rem;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
margin-bottom: 8px;
}
h1 {
margin: 0;
font-size: clamp(1.75rem, 4vw, 3.3rem);
line-height: 1.02;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 860px;
margin: 12px 0 0;
color: var(--muted);
line-height: 1.55;
}
.collection {
min-width: 265px;
padding: 15px 17px;
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(16, 29, 47, 0.84);
box-shadow: 0 16px 50px rgba(0, 0, 0, 0.2);
}
.collection-title {
display: flex;
justify-content: space-between;
gap: 12px;
font-size: 0.76rem;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.09em;
font-weight: 750;
}
.retained {
color: var(--green);
}
#inputStrip {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 12px;
}
.input-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 8px;
background: #0b1626;
border: 1px solid #263d59;
font-variant-numeric: tabular-nums;
}
.input-chip strong {
font-size: 1rem;
}
.input-chip span {
color: var(--muted);
font-size: 0.72rem;
font-weight: 800;
}
.stats {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-bottom: 12px;
}
.stat {
position: relative;
overflow: hidden;
min-height: 104px;
padding: 16px 17px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(16, 29, 47, 0.9);
}
.stat::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 4px;
background: var(--accent, var(--cyan));
}
.stat-label {
color: var(--muted);
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.045em;
}
.stat-value {
margin-top: 5px;
font-size: 2rem;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.stat-note {
margin-top: 3px;
color: var(--muted);
font-size: 0.75rem;
}
.scene-shell {
position: relative;
overflow: hidden;
border: 1px solid var(--border);
border-radius: 16px;
background: #081321;
box-shadow: 0 25px 70px rgba(0, 0, 0, 0.28);
}
#scene {
position: relative;
width: 100%;
height: clamp(470px, 62vh, 680px);
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.scene-hint,
.scene-badge,
.final-badge {
position: absolute;
z-index: 2;
pointer-events: none;
border: 1px solid rgba(127, 164, 201, 0.28);
background: rgba(7, 16, 29, 0.78);
backdrop-filter: blur(8px);
border-radius: 9px;
}
.scene-hint {
left: 14px;
bottom: 14px;
padding: 8px 11px;
color: var(--muted);
font-size: 0.76rem;
}
.scene-badge {
top: 14px;
left: 14px;
padding: 9px 12px;
color: var(--cyan);
font-size: 0.73rem;
font-weight: 850;
letter-spacing: 0.08em;
}
.final-badge {
top: 14px;
right: 14px;
max-width: min(520px, calc(100% - 28px));
padding: 10px 13px;
color: var(--green);
font-size: 0.82rem;
font-weight: 700;
}
.final-badge[hidden] {
display: none;
}
.control-panel {
display: grid;
grid-template-columns: auto minmax(180px, 1fr) auto;
gap: 16px;
align-items: center;
margin-top: 12px;
padding: 14px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(16, 29, 47, 0.92);
}
.buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.scrubber {
display: grid;
grid-template-columns: auto 1fr auto;
gap: 10px;
align-items: center;
color: var(--muted);
font-size: 0.8rem;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
}
.pacing-note {
color: var(--muted);
font-size: 0.75rem;
text-align: right;
max-width: 280px;
line-height: 1.4;
}
.event-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 12px;
}
.event-card,
.convention,
.ledger {
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(16, 29, 47, 0.9);
}
.event-card {
position: relative;
overflow: hidden;
padding: 16px 17px;
}
.event-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 4px;
background: var(--accent);
}
.event-heading {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: baseline;
}
.event-heading strong {
color: var(--accent);
font-size: 0.82rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.event-heading span {
color: var(--muted);
font-size: 0.76rem;
font-variant-numeric: tabular-nums;
}
.event-title {
margin: 11px 0 5px;
font-size: 1.03rem;
font-weight: 800;
}
.event-description {
min-height: 48px;
margin: 0;
color: var(--muted);
line-height: 1.5;
font-size: 0.86rem;
}
.lower-grid {
display: grid;
grid-template-columns: minmax(300px, 0.78fr) minmax(430px, 1.22fr);
gap: 12px;
margin-top: 12px;
}
.convention,
.ledger {
padding: 17px;
}
.convention h2,
.ledger h2 {
margin: 0 0 10px;
font-size: 0.91rem;
letter-spacing: 0.04em;
}
.convention p {
margin: 9px 0;
color: var(--muted);
font-size: 0.84rem;
line-height: 1.55;
}
.convention strong {
color: var(--text);
}
.callout {
padding: 10px 12px;
border-left: 3px solid var(--cyan);
background: #0a1727;
color: #c5d7eb;
border-radius: 0 8px 8px 0;
font-size: 0.81rem;
line-height: 1.5;
}
details summary {
cursor: pointer;
color: var(--cyan);
font-weight: 750;
}
.ledger-intro {
margin: 8px 0 12px;
color: var(--muted);
font-size: 0.79rem;
line-height: 1.45;
}
.operation-columns {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 12px;
}
.operation-column {
min-width: 0;
border: 1px solid #263d59;
border-radius: 9px;
overflow: hidden;
}
.operation-column h3 {
margin: 0;
padding: 9px 10px;
background: #0b1727;
color: var(--muted);
font-size: 0.76rem;
text-transform: uppercase;
letter-spacing: 0.07em;
}
.operation-list {
max-height: 270px;
overflow: auto;
margin: 0;
padding: 0;
list-style: none;
font-family:
ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.71rem;
}
.operation-list li {
padding: 7px 9px;
border-bottom: 1px solid #1e324a;
color: #b9c9dc;
line-height: 1.45;
overflow-wrap: anywhere;
}
.operation-list li:last-child {
border-bottom: 0;
}
.operation-list li.compare {
color: #f7cf82;
background: rgba(255, 184, 107, 0.035);
}
.operation-list li.write {
color: #89e6bd;
background: rgba(113, 230, 168, 0.035);
}
.empty-ops {
padding: 12px;
color: var(--muted);
font-size: 0.78rem;
}
@media (max-width: 950px) {
header {
grid-template-columns: 1fr;
}
.collection {
min-width: 0;
}
.stats {
grid-template-columns: 1fr 1fr;
}
.control-panel {
grid-template-columns: 1fr;
}
.pacing-note {
text-align: left;
max-width: none;
}
.lower-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 660px) {
.app {
width: min(100% - 18px, 1500px);
padding-top: 18px;
}
.stats,
.event-grid,
.operation-columns {
grid-template-columns: 1fr;
}
#scene {
height: 510px;
}
.scene-hint {
right: 14px;
}
.event-description {
min-height: 0;
}
}
</style>
</head>
<body>
<main class="app">
<header>
<div>
<div class="eyebrow">Solid sorting comparison</div>
<h1>Same blocks. Different algorithms.</h1>
<p class="subtitle">
One original collection is shown on two parallel shelves. Insertion sort
works in place on the front shelf; merge sort stages records in the
visibly labeled temporary buffer behind the rear shelf. Every record keeps
a unique identity mark.
</p>
</div>
<aside class="collection" aria-label="Original block collection">
<div class="collection-title">
<span>Original collection</span>
<span class="retained">8 / 8 retained</span>
</div>
<div id="inputStrip"></div>
</aside>
</header>
<section class="stats" aria-label="Algorithm counters">
<article class="stat" style="--accent: var(--orange)">
<div class="stat-label">Insertion · comparisons</div>
<div class="stat-value" id="leftComparisons">0</div>
<div class="stat-note">Value-to-value key comparisons</div>
</article>
<article class="stat" style="--accent: var(--orange)">
<div class="stat-label">Insertion · data moves</div>
<div class="stat-value" id="leftMoves">0</div>
<div class="stat-note">Shifts and key-placement writes</div>
</article>
<article class="stat" style="--accent: var(--cyan)">
<div class="stat-label">Merge · comparisons</div>
<div class="stat-value" id="rightComparisons">0</div>
<div class="stat-note">Value-to-value key comparisons</div>
</article>
<article class="stat" style="--accent: var(--cyan)">
<div class="stat-label">Merge · data moves</div>
<div class="stat-value" id="rightMoves">0</div>
<div class="stat-note" id="mergeMoveNote">Temporary writes included</div>
</article>
</section>
<section class="scene-shell">
<div id="scene">
<div class="scene-badge">ONE INPUT · TWO ALGORITHMS</div>
<div class="final-badge" id="finalBadge" hidden></div>
</div>
<div class="scene-hint">Drag to orbit · wheel to zoom · double-click to reset the camera</div>
</section>
<section class="control-panel" aria-label="Playback controls">
<div class="buttons">
<button id="resetButton" type="button">Reset input</button>
<button id="previousButton" type="button">← Previous</button>
<button id="playButton" class="primary" type="button">Play checkpoints</button>
<button id="nextButton" type="button">Next →</button>
</div>
<label class="scrubber">
<span>Checkpoint</span>
<input id="scrubber" type="range" min="0" max="7" value="0" step="1" />
<span id="stepLabel">0 / 7</span>
</label>
<div class="pacing-note">
A checkpoint is a teaching state, not a fixed unit of work.
Playback speed is not a complexity measurement.
</div>
</section>
<section class="event-grid">
<article class="event-card" style="--accent: var(--orange)">
<div class="event-heading">
<strong>Front shelf · insertion sort</strong>
<span id="leftWork">0 comparisons · 0 moves this step</span>
</div>
<div class="event-title" id="leftTitle">Original arrangement</div>
<p class="event-description" id="leftDescription">
Both algorithms begin with the exact same eight blocks in the exact same order.
</p>
</article>
<article class="event-card" style="--accent: var(--cyan)">
<div class="event-heading">
<strong>Rear shelf · merge sort</strong>
<span id="rightWork">0 comparisons · 0 moves this step</span>
</div>
<div class="event-title" id="rightTitle">Original arrangement</div>
<p class="event-description" id="rightDescription">
The temporary rack begins empty. Temporary writes appear when a segment is staged.
</p>
</article>
</section>
<section class="lower-grid">
<article class="convention">
<h2>Published counting convention</h2>
<p>
<strong>Comparison:</strong> one comparison of two block values.
Ties are still compared. Loop-bound checks, reads, and identity checks are
not comparisons.
</p>
<p>
<strong>Data move:</strong> one write of one block record into an array slot.
An in-place overwrite counts once, even when it rewrites the same index.
Holding the insertion key in a local variable is not a move.
</p>
<p>
<strong>Temporary storage is included:</strong> every write into the merge
temporary buffer counts as one move, and every write from that buffer back
to the shelf counts again. Reads are never moves.
</p>
<p>
Both algorithms are stable: equal-valued blocks retain their original
relative order.
</p>
<div class="callout">
Checkpoints intentionally contain different amounts of primitive work.
One insertion checkpoint is one outer pass; one merge checkpoint is one
completed segment merge. Neither the checkpoint count nor animation speed
should be interpreted as a complexity benchmark.
</div>
</article>
<article class="ledger">
<h2>Primitive operation ledger</h2>
<p class="ledger-intro">
The expandable ledger shows the exact primitive comparisons and writes
represented by the current visual checkpoint.
</p>
<details>
<summary>Show operations for this checkpoint</summary>
<div class="operation-columns">
<section class="operation-column">
<h3>Insertion sort</h3>
<ol class="operation-list" id="leftOperations"></ol>
</section>
<section class="operation-column">
<h3>Merge sort</h3>
<ol class="operation-list" id="rightOperations"></ol>
</section>
</div>
</details>
</article>
</section>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
// ---------------------------------------------------------------------
// Original collection. Values may repeat; IDs are always unique.
// ---------------------------------------------------------------------
const records = [
{ id: "A", value: 5, color: 0xff6b6b },
{ id: "B", value: 2, color: 0x4dd4ff },
{ id: "C", value: 8, color: 0xa78bfa },
{ id: "D", value: 1, color: 0x4ade80 },
{ id: "E", value: 4, color: 0xfbbf24 },
{ id: "F", value: 3, color: 0x60a5fa },
{ id: "G", value: 2, color: 0xf472b6 },
{ id: "H", value: 7, color: 0xfb923c }
];
const recordById = new Map(records.map((record) => [record.id, record]));
const originalIds = records.map((record) => record.id);
const N = records.length;
const valueOf = (id) => recordById.get(id).value;
for (const record of records) {
const chip = document.createElement("span");
chip.className = "input-chip";
chip.innerHTML = `<strong>${record.value}</strong><span>#${record.id}</span>`;
$("inputStrip").appendChild(chip);
}
// ---------------------------------------------------------------------
// Insertion-sort checkpoints.
//
// Convention:
// comparison = one key-to-key value comparison
// move = one write of a record into an array slot
// ---------------------------------------------------------------------
function buildInsertionCheckpoints() {
const order = originalIds.slice();
const checkpoints = [];
let comparisons = 0;
let moves = 0;
checkpoints.push({
order: order.slice(),
comparisons,
moves,
pass: 0,
focusId: null,
focusIndex: null,
operations: [],
summary: "Both algorithms begin with the exact same eight blocks in the exact same order."
});
for (let i = 1; i < N; i++) {
const previousComparisons = comparisons;
const previousMoves = moves;
const operations = [];
// Holding this ID in a local variable is not a data move.
const keyId = order[i];
let j = i - 1;
const shiftedIds = [];
while (j >= 0) {
comparisons++;
const leftId = order[j];
const greater = valueOf(leftId) > valueOf(keyId);
operations.push({
type: "compare",
text:
`COMPARE shelf[${j}] #${leftId} (${valueOf(leftId)}) ` +
`> key #${keyId} (${valueOf(keyId)}) → ${greater}`
});
if (!greater) {
break;
}
// One array-slot write is one data move.
order[j + 1] = order[j];
moves++;
operations.push({
type: "write",
text: `WRITE shelf[${j + 1}] ← #${order[j + 1]} (${valueOf(order[j + 1])})`
});
shiftedIds.push(order[j + 1]);
j--;
}
const finalIndex = j + 1;
order[finalIndex] = keyId;
moves++;
operations.push({
type: "write",
text: `WRITE shelf[${finalIndex}] ← #${keyId} (${valueOf(keyId)})`
});
const passComparisons = comparisons - previousComparisons;
const passMoves = moves - previousMoves;
checkpoints.push({
order: order.slice(),
comparisons,
moves,
pass: i,
passComparisons,
passMoves,
focusId: keyId,
focusIndex: finalIndex,
operations,
summary:
`Inserted key #${keyId} (${valueOf(keyId)}) at shelf index ${finalIndex}. ` +
`This pass shifted ${shiftedIds.length} block${shiftedIds.length === 1 ? "" : "s"}, ` +
`used ${passComparisons} comparison${passComparisons === 1 ? "" : "s"}, ` +
`and performed ${passMoves} write${passMoves === 1 ? "" : "s"}.`
});
}
checkpoints[checkpoints.length - 1].complete = true;
return checkpoints;
}
// ---------------------------------------------------------------------
// Top-down merge-sort checkpoints.
//
// For each merge:
// 1. Copy the segment into temporary storage.
// 2. Read from temporary storage and write the merged result to shelf.
//
// Temporary writes and shelf writes both count as data moves.
// ---------------------------------------------------------------------
function buildMergeCheckpoints() {
const order = originalIds.slice();
const temporary = Array(N).fill(null);
const checkpoints = [];
let comparisons = 0;
let moves = 0;
let temporaryWrites = 0;
let outputWrites = 0;
checkpoints.push({
order: order.slice(),
comparisons,
moves,
temporaryWrites,
outputWrites,
segment: null,
temporarySegment: null,
operations: [],
summary:
"The temporary rack begins empty. Temporary writes appear when a segment is staged."
});
function mergeSort(left, right) {
if (left >= right) {
return;
}
const middle = Math.floor((left + right) / 2);
mergeSort(left, middle);
mergeSort(middle + 1, right);
const operations = [];
const previousComparisons = comparisons;
const previousMoves = moves;
// Stage the current segment in the visible temporary buffer.
for (let k = left; k <= right; k++) {
temporary[k] = order[k];
moves++;
temporaryWrites++;
operations.push({
type: "write",
text:
`WRITE temp[${k}] ← #${temporary[k]} (${valueOf(temporary[k])}) ` +
`[temporary write; 1 move]`
});
}
// Keep the staged segment visible at this checkpoint.
const stagedIds = temporary.slice(left, right + 1);
let i = left;
let j = middle + 1;
let k = left;
while (i <= middle && j <= right) {
comparisons++;
const leftId = temporary[i];
const rightId = temporary[j];
const takeLeft = valueOf(leftId) <= valueOf(rightId);
operations.push({
type: "compare",
text:
`COMPARE temp[${i}] #${leftId} (${valueOf(leftId)}) ≤ ` +
`temp[${j}] #${rightId} (${valueOf(rightId)}) → ${takeLeft}`
});
const chosenId = takeLeft ? temporary[i] : temporary[j];
order[k] = chosenId;
moves++;
outputWrites++;
operations.push({
type: "write",
text: `WRITE shelf[${k}] ← #${chosenId} (${valueOf(chosenId)})`
});
if (takeLeft) {
i++;
} else {
j++;
}
k++;
}
while (i <= middle) {
const chosenId = temporary[i];
order[k] = chosenId;
moves++;
outputWrites++;
operations.push({
type: "write",
text: `WRITE shelf[${k}] ← #${chosenId} (${valueOf(chosenId)})`
});
i++;
k++;
}
while (j <= right) {
const chosenId = temporary[j];
order[k] = chosenId;
moves++;
outputWrites++;
operations.push({
type: "write",
text: `WRITE shelf[${k}] ← #${chosenId} (${valueOf(chosenId)})`
});
j++;
k++;
}
const mergeComparisons = comparisons - previousComparisons;
const mergeMoves = moves - previousMoves;
checkpoints.push({
order: order.slice(),
comparisons,
moves,
temporaryWrites,
outputWrites,
segment: { left, right },
temporarySegment: { left, right, ids: stagedIds },
mergeComparisons,
mergeMoves,
operations,
summary:
`Merged shelf segment [${left}…${right}]. ` +
`${mergeComparisons} key comparison${mergeComparisons === 1 ? "" : "s"} were made. ` +
`${mergeMoves} writes were performed: ${right - left + 1} into temporary storage ` +
`and ${right - left + 1} merged writes back to the shelf.`
});
}
mergeSort(0, N - 1);
checkpoints[checkpoints.length - 1].complete = true;
return checkpoints;
}
const insertionCheckpoints = buildInsertionCheckpoints();
const mergeCheckpoints = buildMergeCheckpoints();
// Both sides contain exactly the original records at every checkpoint.
function isOriginalPermutation(ids) {
return (
ids.length === originalIds.length &&
new Set(ids).size === originalIds.length &&
originalIds.every((id) => ids.includes(id))
);
}
function isSortedByValue(ids) {
for (let i = 1; i < ids.length; i++) {
if (valueOf(ids[i - 1]) > valueOf(ids[i])) {
return false;
}
}
return true;
}
for (const checkpoint of insertionCheckpoints) {
if (!isOriginalPermutation(checkpoint.order)) {
throw new Error("Insertion checkpoint lost or duplicated an original block.");
}
}
for (const checkpoint of mergeCheckpoints) {
if (!isOriginalPermutation(checkpoint.order)) {
throw new Error("Merge checkpoint lost or duplicated an original block.");
}
}
if (
!isSortedByValue(insertionCheckpoints.at(-1).order) ||
!isSortedByValue(mergeCheckpoints.at(-1).order)
) {
throw new Error("A final sorted result failed validation.");
}
// One global checkpoint advances each unfinished algorithm to its next
// meaningful checkpoint. The algorithms need not use equal primitive work.
const totalSteps = Math.max(
insertionCheckpoints.length,
mergeCheckpoints.length
) - 1;
const timeline = [];
for (let step = 0; step <= totalSteps; step++) {
const leftIndex = Math.min(step, insertionCheckpoints.length - 1);
const rightIndex = Math.min(step, mergeCheckpoints.length - 1);
timeline.push({
left: insertionCheckpoints[leftIndex],
right: mergeCheckpoints[rightIndex]
});
}
$("scrubber").max = String(totalSteps);
// ---------------------------------------------------------------------
// Three.js scene.
// ---------------------------------------------------------------------
const host = $("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x081321);
scene.fog = new THREE.Fog(0x081321, 26, 48);
const camera = new THREE.PerspectiveCamera(
44,
host.clientWidth / host.clientHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(host.clientWidth, host.clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D visualization of insertion sort and merge sort"
);
host.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xccecff, 0x182033, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(7, 15, 11);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -16;
keyLight.shadow.camera.right = 16;
keyLight.shadow.camera.top = 16;
keyLight.shadow.camera.bottom = -16;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5b8dff, 2.1);
rimLight.position.set(-10, 7, -9);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x091523,
roughness: 0.93,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.62;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(44, 44, 0x1c3550, 0x10263a);
grid.position.y = -0.605;
grid.material.transparent = true;
grid.material.opacity = 0.38;
scene.add(grid);
const random = (min, max) => min + Math.random() * (max - min);
const dustPositions = new Float32Array(180 * 3);
for (let i = 0; i < 180; i++) {
dustPositions[i * 3] = random(-18, 18);
dustPositions[i * 3 + 1] = random(0.5, 15);
dustPositions[i * 3 + 2] = random(-18, 12);
}
const dustGeometry = new THREE.BufferGeometry();
dustGeometry.setAttribute(
"position",
new THREE.BufferAttribute(dustPositions, 3)
);
const dust = new THREE.Points(
dustGeometry,
new THREE.PointsMaterial({
color: 0x7bbcff,
size: 0.045,
transparent: true,
opacity: 0.36
})
);
scene.add(dust);
const SLOT = 1.28;
const BLOCK_WIDTH = 1.04;
const BLOCK_HEIGHT = 1.34;
const BLOCK_DEPTH = 0.82;
const SHELF_LENGTH = N * SLOT + 0.58;
const INSERTION_Z = 2.7;
const MERGE_Z = -2.7;
const TEMP_Z = -4.5;
const TEMP_SURFACE = 1.16;
const slotX = (index) => (index - (N - 1) / 2) * SLOT;
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.lineTo(x + width - r, y);
context.quadraticCurveTo(x + width, y, x + width, y + r);
context.lineTo(x + width, y + height - r);
context.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
context.lineTo(x + r, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - r);
context.lineTo(x, y + r);
context.quadraticCurveTo(x, y, x + r, y);
context.closePath();
}
function makeTextSprite(
text,
{
color = "#dcecff",
background = "rgba(7,16,29,0.82)",
border = "#365372",
width = 512,
height = 128,
fontSize = 47,
fontWeight = 800
} = {}
) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
roundedRect(context, 3, 3, width - 6, height - 6, 20);
context.fillStyle = background;
context.fill();
context.strokeStyle = border;
context.lineWidth = 4;
context.stroke();
context.fillStyle = color;
context.font = `${fontWeight} ${fontSize}px system-ui, sans-serif`;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, width / 2, height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
function makeBlockLabel(record) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 256, 256);
roundedRect(context, 17, 14, 222, 228, 26);
context.fillStyle = "rgba(6,13,24,0.80)";
context.fill();
context.strokeStyle = "rgba(255,255,255,0.26)";
context.lineWidth = 4;
context.stroke();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "#ffffff";
context.font = "900 98px system-ui, sans-serif";
context.fillText(String(record.value), 128, 101);
context.fillStyle = "#c9e4ff";
context.font = "800 52px system-ui, sans-serif";
context.fillText(`#${record.id}`, 128, 188);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
return new THREE.Mesh(
new THREE.PlaneGeometry(0.88, 1.06),
new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
}
function makeShelf(z, accent, temporary = false) {
const group = new THREE.Group();
const surfaceY = temporary ? TEMP_SURFACE : 0;
const boardY = surfaceY - 0.12;
const board = new THREE.Mesh(
new THREE.BoxGeometry(SHELF_LENGTH, 0.24, 1.56),
new THREE.MeshStandardMaterial({
color: temporary ? 0x162c42 : 0x17283d,
roughness: 0.58,
metalness: 0.28
})
);
board.position.set(0, boardY, z);
board.castShadow = true;
board.receiveShadow = true;
group.add(board);
const edge = new THREE.Mesh(
new THREE.BoxGeometry(SHELF_LENGTH, 0.055, 0.075),
new THREE.MeshStandardMaterial({
color: accent,
emissive: accent,
emissiveIntensity: 1.7,
roughness: 0.35
})
);
edge.position.set(0, surfaceY + 0.015, z + 0.745);
group.add(edge);
for (let i = 0; i < N; i++) {
const pad = new THREE.Mesh(
new THREE.BoxGeometry(1.08, 0.035, 1.02),
new THREE.MeshStandardMaterial({
color: temporary ? 0x10283b : 0x102034,
roughness: 0.72,
metalness: 0.16
})
);
pad.position.set(slotX(i), surfaceY + 0.018, z);
pad.receiveShadow = true;
group.add(pad);
const label = makeTextSprite(temporary ? `T${i}` : `${i}`, {
color: temporary ? "#8eeeff" : "#7894b4",
background: "rgba(5,13,24,0.55)",
border: "rgba(65,94,124,0.28)",
width: 256,
height: 96,
fontSize: 43
});
label.scale.set(0.43, 0.16, 1);
label.position.set(
slotX(i),
surfaceY - 0.02,
z + (temporary ? 0.86 : 0.84)
);
group.add(label);
}
scene.add(group);
return group;
}
makeShelf(INSERTION_Z, 0xffa557);
makeShelf(MERGE_Z, 0x52d9ff);
makeShelf(TEMP_Z, 0x9b8cff, true);
const insertionLabel = makeTextSprite("INSERTION SORT · FRONT SHELF", {
color: "#ffbd7d",
border: "#714b31"
});
insertionLabel.scale.set(4.35, 1.08, 1);
insertionLabel.position.set(-5.95, 1.55, INSERTION_Z);
scene.add(insertionLabel);
const mergeLabel = makeTextSprite("MERGE SORT · REAR SHELF", {
color: "#75e9ff",
border: "#2a6074"
});
mergeLabel.scale.set(4.25, 1.06, 1);
mergeLabel.position.set(-5.9, 1.55, MERGE_Z);
scene.add(mergeLabel);
const temporaryLabel = makeTextSprite(
"TEMPORARY BUFFER · EVERY WRITE COUNTS AS A MOVE",
{
color: "#c8bdff",
border: "#5b4d82",
width: 640,
height: 110,
fontSize: 34
}
);
temporaryLabel.scale.set(5.3, 0.91, 1);
temporaryLabel.position.set(-4.95, 2.48, TEMP_Z);
scene.add(temporaryLabel);
const sharedBlockGeometry = new THREE.BoxGeometry(
BLOCK_WIDTH,
BLOCK_HEIGHT,
BLOCK_DEPTH
);
const sharedEdgesGeometry = new THREE.EdgesGeometry(sharedBlockGeometry);
const leftBlocks = new Map();
const rightBlocks = new Map();
const temporaryBlocks = new Map();
function makeBlock(record) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: record.color,
roughness: 0.36,
metalness: 0.16,
emissive: 0x000000,
emissiveIntensity: 0
});
const body = new THREE.Mesh(sharedBlockGeometry, material);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const edges = new THREE.LineSegments(
sharedEdgesGeometry,
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.42
})
);
group.add(edges);
const label = makeBlockLabel(record);
label.position.set(0, 0.015, BLOCK_DEPTH / 2 + 0.008);
group.add(label);
group.userData.target = new THREE.Vector3();
group.userData.targetScale = 1;
group.userData.material = material;
return group;
}
for (const record of records) {
const left = makeBlock(record);
const right = makeBlock(record);
const temp = makeBlock(record);
leftBlocks.set(record.id, left);
rightBlocks.set(record.id, right);
temporaryBlocks.set(record.id, temp);
scene.add(left, right, temp);
}
function makeHalo(color) {
const geometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(1, 1, 1)
);
const line = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
line.renderOrder = 15;
line.visible = false;
scene.add(line);
return line;
}
const insertionHalo = makeHalo(0xffb86b);
const mergeHalo = makeHalo(0x5ee7ff);
const temporaryHalo = makeHalo(0xbdaeff);
// ---------------------------------------------------------------------
// Direct camera controls. No Three.js examples/addons are imported.
// ---------------------------------------------------------------------
const cameraState = {
yaw: 0.29,
pitch: 0.48,
radius: 24
};
const cameraTarget = new THREE.Vector3(0, 1.35, -0.45);
let dragging = false;
let dragX = 0;
let dragY = 0;
function updateCamera() {
const { yaw, pitch, radius } = cameraState;
camera.position.set(
cameraTarget.x + radius * Math.sin(yaw) * Math.cos(pitch),
cameraTarget.y + radius * Math.sin(pitch),
cameraTarget.z + radius * Math.cos(yaw) * Math.cos(pitch)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraState.yaw = 0.29;
cameraState.pitch = 0.48;
cameraState.radius = 24;
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) {
return;
}
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
cameraState.yaw -= dx * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.004,
0.18,
1.05
);
dragX = event.clientX;
dragY = event.clientY;
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
15,
36
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
updateCamera();
// ---------------------------------------------------------------------
// Checkpoint-to-visual-state mapping.
// ---------------------------------------------------------------------
let currentStep = 0;
let playing = false;
let playTimer = null;
function setBlockTarget(block, x, y, z, scale = 1) {
block.userData.target.set(x, y, z);
block.userData.targetScale = scale;
}
function setGlow(block, active, color = 0x0b6070) {
block.userData.material.emissive.setHex(active ? color : 0x000000);
block.userData.material.emissiveIntensity = active ? 0.34 : 0;
}
function applyStep(step, immediate = false) {
currentStep = THREE.MathUtils.clamp(step, 0, totalSteps);
const snapshot = timeline[currentStep];
const leftPositions = new Map(
snapshot.left.order.map((id, index) => [id, index])
);
const rightPositions = new Map(
snapshot.right.order.map((id, index) => [id, index])
);
const temporaryPositions = new Map();
if (snapshot.right.temporarySegment) {
const segment = snapshot.right.temporarySegment;
segment.ids.forEach((id, offset) => {
temporaryPositions.set(id, segment.left + offset);
});
}
for (const record of records) {
const id = record.id;
const leftBlock = leftBlocks.get(id);
const rightBlock = rightBlocks.get(id);
const tempBlock = temporaryBlocks.get(id);
setBlockTarget(
leftBlock,
slotX(leftPositions.get(id)),
BLOCK_HEIGHT / 2,
INSERTION_Z
);
setBlockTarget(
rightBlock,
slotX(rightPositions.get(id)),
BLOCK_HEIGHT / 2,
MERGE_Z
);
if (temporaryPositions.has(id)) {
setBlockTarget(
tempBlock,
slotX(temporaryPositions.get(id)),
TEMP_SURFACE + (BLOCK_HEIGHT * 0.56) / 2,
TEMP_Z,
0.56
);
tempBlock.visible = true;
} else {
setBlockTarget(
tempBlock,
tempBlock.position.x,
TEMP_SURFACE + (BLOCK_HEIGHT * 0.56) / 2,
TEMP_Z,
0
);
}
setGlow(leftBlock, id === snapshot.left.focusId, 0x8a4b17);
setGlow(
rightBlock,
Boolean(snapshot.right.segment),
0x075d75
);
setGlow(
tempBlock,
temporaryPositions.has(id),
0x49358a
);
}
// Insertion focus halo.
if (
snapshot.left.focusId !== null &&
snapshot.left.focusIndex !== null
) {
insertionHalo.visible = true;
insertionHalo.scale.set(1.16, 1.45, 0.94);
insertionHalo.position.set(
slotX(snapshot.left.focusIndex),
BLOCK_HEIGHT / 2,
INSERTION_Z
);
} else {
insertionHalo.visible = false;
}
// Merge segment halo.
if (snapshot.right.segment) {
const { left, right } = snapshot.right.segment;
const count = right - left + 1;
const middle = (left + right) / 2;
mergeHalo.visible = true;
mergeHalo.scale.set(count * SLOT - 0.12, 1.45, 0.94);
mergeHalo.position.set(
slotX(middle),
BLOCK_HEIGHT / 2,
MERGE_Z
);
temporaryHalo.visible = true;
temporaryHalo.scale.set(count * SLOT - 0.12, 0.86, 0.67);
temporaryHalo.position.set(
slotX(middle),
TEMP_SURFACE + (BLOCK_HEIGHT * 0.56) / 2,
TEMP_Z
);
} else {
mergeHalo.visible = false;
temporaryHalo.visible = false;
}
if (immediate) {
for (const block of [
...leftBlocks.values(),
...rightBlocks.values(),
...temporaryBlocks.values()
]) {
block.position.copy(block.userData.target);
block.scale.setScalar(block.userData.targetScale);
}
}
updateInterface();
}
function populateOperationList(element, operations) {
element.replaceChildren();
if (!operations || operations.length === 0) {
const empty = document.createElement("li");
empty.className = "empty-ops";
empty.textContent = "No primitive operation in this checkpoint.";
element.appendChild(empty);
return;
}
for (const operation of operations) {
const item = document.createElement("li");
item.className = operation.type;
item.textContent = operation.text;
element.appendChild(item);
}
}
function describeSortedOrder(ids) {
return ids
.map((id) => `${valueOf(id)}#${id}`)
.join(" · ");
}
function updateInterface() {
const snapshot = timeline[currentStep];
const left = snapshot.left;
const right = snapshot.right;
$("leftComparisons").textContent = String(left.comparisons);
$("leftMoves").textContent = String(left.moves);
$("rightComparisons").textContent = String(right.comparisons);
$("rightMoves").textContent = String(right.moves);
$("mergeMoveNote").textContent =
`${right.temporaryWrites} temp writes + ` +
`${right.outputWrites} shelf writes`;
$("stepLabel").textContent = `${currentStep} / ${totalSteps}`;
$("scrubber").value = String(currentStep);
$("leftWork").textContent =
`${left.passComparisons ?? 0} comparisons · ` +
`${left.passMoves ?? 0} moves this step`;
$("rightWork").textContent =
`${right.mergeComparisons ?? 0} comparisons · ` +
`${right.mergeMoves ?? 0} moves this step`;
$("leftTitle").textContent = left.complete
? "Sorted result · all original blocks retained"
: left.pass === 0
? "Original arrangement"
: `Pass ${left.pass} of ${N - 1} · key #${left.focusId} (${valueOf(left.focusId)})`;
$("rightTitle").textContent = right.complete
? "Sorted result · temporary records remain visibly staged"
: right.segment
? `Completed merge of segment [${right.segment.left}…${right.segment.right}]`
: "Original arrangement";
$("leftDescription").textContent = left.summary;
$("rightDescription").textContent = right.summary;
populateOperationList($("leftOperations"), left.operations);
populateOperationList($("rightOperations"), right.operations);
$("previousButton").disabled = currentStep === 0;
$("nextButton").disabled = currentStep === totalSteps;
const finalBadge = $("finalBadge");
if (currentStep === totalSteps) {
finalBadge.hidden = false;
finalBadge.textContent =
`Both shelves are sorted: ${describeSortedOrder(right.order)}. ` +
"The original A–H collection is intact.";
} else {
finalBadge.hidden = true;
}
}
function stopPlayback() {
playing = false;
if (playTimer !== null) {
clearInterval(playTimer);
playTimer = null;
}
$("playButton").textContent = "Play checkpoints";
}
function startPlayback() {
if (currentStep >= totalSteps) {
applyStep(0);
}
playing = true;
$("playButton").textContent = "Pause";
playTimer = setInterval(() => {
if (currentStep >= totalSteps) {
stopPlayback();
return;
}
applyStep(currentStep + 1);
}, 1900);
}
$("resetButton").addEventListener("click", () => {
stopPlayback();
applyStep(0, true);
});
$("previousButton").addEventListener("click", () => {
stopPlayback();
applyStep(currentStep - 1);
});
$("nextButton").addEventListener("click", () => {
stopPlayback();
applyStep(currentStep + 1);
});
$("playButton").addEventListener("click", () => {
if (playing) {
stopPlayback();
} else {
startPlayback();
}
});
$("scrubber").addEventListener("input", (event) => {
stopPlayback();
applyStep(Number(event.target.value));
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) {
return;
}
if (event.key === "ArrowRight") {
stopPlayback();
applyStep(currentStep + 1);
} else if (event.key === "ArrowLeft") {
stopPlayback();
applyStep(currentStep - 1);
} else if (event.code === "Space") {
event.preventDefault();
if (playing) {
stopPlayback();
} else {
startPlayback();
}
}
});
function resizeRenderer() {
const width = host.clientWidth;
const height = host.clientHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
if ("ResizeObserver" in window) {
new ResizeObserver(resizeRenderer).observe(host);
} else {
window.addEventListener("resize", resizeRenderer);
}
// ---------------------------------------------------------------------
// Render loop and eased block motion.
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
const easing = 1 - Math.exp(-delta * 9);
for (const block of [
...leftBlocks.values(),
...rightBlocks.values(),
...temporaryBlocks.values()
]) {
block.position.lerp(block.userData.target, easing);
const nextScale = THREE.MathUtils.lerp(
block.scale.x,
block.userData.targetScale,
easing
);
block.scale.setScalar(nextScale);
if (block.userData.targetScale === 0 && nextScale < 0.01) {
block.visible = false;
} else {
block.visible = true;
}
}
dust.rotation.y += delta * 0.006;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
applyStep(0, true);
resizeRenderer();
animate();
</script>
</body>
</html>
```