Prompt specification
Build or customize the Three.js 3D scene "Sorting invariant inspection tool" 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: Sorting invariant inspection tool
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/sorting-invariant-inspection-tool-x1908
Scene Description Prompt:
I'd like to see this as a low-poly Three.js scene: sorting invariant inspection tool. Let users step through a chosen sorting algorithm and inspect its current invariant; verify the final ordered sequence and unchanged multiset, including duplicate-key cases. Use cdnjs and return one self-contained HTML file.
Acceptance checks: Keep the toolbar separate from a visible, independently sized canvas. Include a small duplicate-key example, per-step invariant evidence, and final sorted-order and multiset checks driven by the actual displayed data.
Return a single complete HTML document. It must work in a sandbox that allows scripts, with the cdnjs Three.js r160 module and inline CSS. Use procedural geometry and local button handlers; no native form submission, pointer lock, remote assets, or runtime network requests besides Three.js.
Working Three.js Starter (sorting-invariant-inspection-tool-x1908):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="dark">
<link rel="icon" href="data:,">
<title>Invariant Lab — Sorting Inspection Tool</title>
<style>
:root {
--bg: #08111f;
--panel: #101b2c;
--panel-2: #142238;
--line: #263750;
--text: #eaf2ff;
--muted: #91a4bd;
--cyan: #54d8d0;
--green: #78e08f;
--amber: #f2b866;
--red: #ff7f88;
--blue: #75a7ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
body {
display: grid;
grid-template-rows: auto minmax(0, 1fr);
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
select,
input {
font: inherit;
}
button,
select {
color: var(--text);
background: #17263c;
border: 1px solid #344963;
border-radius: 8px;
}
button {
min-height: 36px;
padding: 7px 11px;
cursor: pointer;
transition: border-color 120ms ease, background 120ms ease, transform 120ms ease;
}
button:hover:not(:disabled) {
border-color: var(--cyan);
background: #1c3049;
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:disabled {
cursor: not-allowed;
opacity: 0.38;
}
button.primary {
color: #07131d;
border-color: var(--cyan);
background: var(--cyan);
font-weight: 750;
}
button.primary:hover:not(:disabled) {
background: #79e9e1;
}
select {
width: 100%;
min-height: 36px;
padding: 7px 30px 7px 9px;
cursor: pointer;
}
.toolbar {
position: relative;
z-index: 10;
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: end;
gap: 18px;
padding: 10px 14px;
background: linear-gradient(180deg, #111e31, #0c1727);
border-bottom: 1px solid var(--line);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.22);
}
.brand {
display: flex;
align-items: center;
gap: 10px;
min-width: 190px;
padding-bottom: 2px;
}
.brand-mark {
position: relative;
width: 31px;
height: 31px;
flex: 0 0 auto;
border: 2px solid var(--cyan);
border-radius: 8px 3px 8px 3px;
transform: rotate(-8deg);
box-shadow: inset 8px 0 0 rgba(84, 216, 208, 0.18);
}
.brand-mark::after {
content: "";
position: absolute;
left: 6px;
right: 6px;
top: 12px;
height: 3px;
background: var(--cyan);
transform: rotate(-8deg);
}
.brand strong {
display: block;
font-size: 15px;
letter-spacing: 0.02em;
}
.brand small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 11px;
}
.toolbar-controls {
display: flex;
align-items: end;
justify-content: flex-end;
gap: 9px;
min-width: 0;
flex-wrap: wrap;
}
.control {
display: grid;
gap: 4px;
min-width: 132px;
}
.control.compact {
min-width: 92px;
}
.control > span {
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.button-row {
display: flex;
gap: 6px;
}
main {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
min-width: 0;
min-height: 0;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
isolation: isolate;
background:
radial-gradient(circle at 50% 42%, rgba(40, 73, 108, 0.28), transparent 42%),
#08111f;
}
#canvasHost {
position: absolute;
inset: 0;
min-width: 0;
min-height: 0;
}
#canvasHost canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
touch-action: none;
}
#canvasHost canvas.dragging {
cursor: grabbing;
}
#labels {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.bar-label {
position: absolute;
display: flex;
align-items: center;
gap: 4px;
padding: 4px 6px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 6px;
background: rgba(6, 13, 23, 0.82);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.22);
color: #f6f9ff;
font-size: 11px;
line-height: 1;
white-space: nowrap;
transform: translate(-50%, -100%);
backdrop-filter: blur(5px);
}
.bar-label strong {
color: #fff;
font-size: 12px;
}
.bar-label .item-id {
color: #9fb2ca;
font-size: 9px;
}
.bar-label .duplicate-count {
padding: 2px 3px;
border-radius: 4px;
color: #fff2cf;
background: rgba(242, 184, 102, 0.32);
font-size: 9px;
font-weight: 800;
}
.scene-hud {
position: absolute;
z-index: 3;
pointer-events: none;
}
.scene-heading {
top: 15px;
left: 16px;
max-width: min(520px, calc(100% - 32px));
padding: 10px 12px;
border: 1px solid rgba(107, 137, 174, 0.24);
border-radius: 9px;
background: rgba(8, 17, 31, 0.76);
backdrop-filter: blur(8px);
}
.scene-heading .eyebrow {
margin-bottom: 3px;
color: var(--cyan);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#sceneTitle {
font-size: 14px;
font-weight: 750;
}
#scenePhase {
margin-top: 4px;
color: #b8c7da;
font-size: 11px;
}
.scene-legend {
left: 16px;
bottom: 14px;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
max-width: calc(100% - 32px);
padding: 8px 10px;
border: 1px solid rgba(107, 137, 174, 0.22);
border-radius: 8px;
background: rgba(8, 17, 31, 0.76);
color: #b8c7da;
font-size: 10px;
backdrop-filter: blur(8px);
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 5px;
white-space: nowrap;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
box-shadow: 0 0 8px currentColor;
}
.legend-dot.established {
color: var(--cyan);
background: var(--cyan);
}
.legend-dot.active {
color: var(--amber);
background: var(--amber);
}
.camera-hint {
right: 14px;
bottom: 15px;
color: rgba(207, 220, 237, 0.65);
font-size: 10px;
text-shadow: 0 1px 3px #000;
}
.inspector {
min-width: 0;
min-height: 0;
overflow: auto;
padding: 13px;
background: #0d1726;
border-left: 1px solid var(--line);
scrollbar-color: #354b67 #0d1726;
}
.panel {
margin-bottom: 11px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 11px;
background: linear-gradient(180deg, rgba(20, 34, 56, 0.96), rgba(15, 27, 45, 0.96));
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}
.panel:last-child {
margin-bottom: 0;
}
.panel h2 {
margin: 0 0 7px;
font-size: 13px;
letter-spacing: 0.015em;
}
.panel p {
margin: 0;
color: #b7c6d9;
font-size: 12px;
line-height: 1.48;
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.step-heading {
display: flex;
align-items: start;
justify-content: space-between;
gap: 10px;
}
#stepTitle {
margin: 0;
font-size: 17px;
line-height: 1.18;
}
#stepCounter {
flex: 0 0 auto;
padding: 4px 6px;
border-radius: 5px;
background: #20334e;
color: #c9d8ea;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
#phaseText {
margin-top: 8px;
}
#stepRange {
width: 100%;
margin: 12px 0 4px;
accent-color: var(--cyan);
cursor: pointer;
}
.range-caption {
display: flex;
justify-content: space-between;
color: #778ba4;
font-size: 9px;
}
.subheading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 13px 0 7px;
color: #91a4bd;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.array-chips {
display: flex;
gap: 5px;
flex-wrap: wrap;
}
.array-chip {
display: inline-flex;
align-items: baseline;
gap: 4px;
min-width: 37px;
justify-content: center;
padding: 6px 7px;
border: 1px solid #38506d;
border-radius: 6px;
background: #172940;
color: #f4f8ff;
font-size: 12px;
font-weight: 800;
}
.array-chip small {
color: #8fa4bf;
font-size: 8px;
font-weight: 650;
}
.algorithm-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 6px;
}
#algorithmName {
font-size: 13px;
font-weight: 800;
}
.checkpoint-chip {
padding: 3px 6px;
border: 1px solid #35506d;
border-radius: 999px;
color: #9fb4cd;
font-size: 9px;
}
#invariantText {
margin-bottom: 10px;
color: #dce7f5;
font-size: 12px;
line-height: 1.5;
}
.evidence-list {
display: grid;
gap: 7px;
margin: 0;
padding: 0;
list-style: none;
}
.evidence-row {
display: grid;
grid-template-columns: 23px minmax(0, 1fr);
gap: 8px;
padding: 8px;
border: 1px solid #29405b;
border-radius: 7px;
background: rgba(9, 19, 33, 0.58);
}
.evidence-icon {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border-radius: 50%;
color: #082019;
background: var(--green);
font-size: 12px;
font-weight: 900;
}
.evidence-title {
display: block;
color: #e8f0fb;
font-size: 11px;
font-weight: 780;
}
.evidence-detail {
display: block;
margin-top: 2px;
color: #94a8c0;
font-size: 10px;
line-height: 1.38;
overflow-wrap: anywhere;
}
.final-status {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 10px;
padding: 10px;
border: 1px solid #314965;
border-radius: 8px;
background: #111f32;
}
.final-status.pass {
border-color: rgba(120, 224, 143, 0.58);
background: rgba(55, 122, 76, 0.18);
}
.final-status.fail {
border-color: rgba(255, 127, 136, 0.65);
background: rgba(143, 48, 58, 0.2);
}
.status-icon {
display: grid;
place-items: center;
width: 31px;
height: 31px;
flex: 0 0 auto;
border-radius: 50%;
color: #101a28;
background: #8798ae;
font-size: 16px;
font-weight: 900;
}
.final-status.pass .status-icon {
background: var(--green);
}
.final-status.fail .status-icon {
background: var(--red);
}
.status-copy strong {
display: block;
font-size: 12px;
}
.status-copy span {
display: block;
margin-top: 2px;
color: #a9bad0;
font-size: 10px;
line-height: 1.35;
}
.check-list {
display: grid;
gap: 7px;
}
.check-row {
display: grid;
grid-template-columns: 24px minmax(0, 1fr);
gap: 8px;
padding: 8px;
border: 1px solid #2a405b;
border-radius: 7px;
background: rgba(8, 17, 30, 0.55);
}
.check-mark {
display: grid;
place-items: center;
width: 23px;
height: 23px;
border-radius: 50%;
background: #7b8da4;
color: #07111e;
font-size: 12px;
font-weight: 900;
}
.check-row.pass .check-mark {
background: var(--green);
}
.check-row.fail .check-mark {
background: var(--red);
}
.check-row.pending .check-mark {
background: var(--amber);
}
.check-title {
display: block;
font-size: 11px;
font-weight: 780;
}
.check-detail {
display: block;
margin-top: 2px;
color: #91a5bd;
font-size: 10px;
line-height: 1.4;
overflow-wrap: anywhere;
}
.sequence-box {
margin-top: 9px;
padding: 8px;
border: 1px solid #293f5a;
border-radius: 7px;
background: #0b1727;
}
.sequence-box span {
display: block;
margin-bottom: 4px;
color: #7f93ac;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.sequence-box code {
color: #dbe8f8;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
overflow-wrap: anywhere;
}
.histogram-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 8px;
}
.histogram-cell {
padding: 8px;
border: 1px solid #293f5a;
border-radius: 7px;
background: #0b1727;
}
.histogram-cell span {
display: block;
margin-bottom: 4px;
color: #7f93ac;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.histogram-cell code {
color: #dbe8f8;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.45;
overflow-wrap: anywhere;
}
.data-note {
margin-top: 9px;
padding: 8px;
border-left: 3px solid var(--amber);
border-radius: 4px;
background: rgba(242, 184, 102, 0.08);
color: #c4cfdd;
font-size: 10px;
line-height: 1.42;
}
@media (max-width: 1050px) {
.toolbar {
grid-template-columns: 1fr;
gap: 8px;
}
.brand {
min-width: 0;
}
.toolbar-controls {
justify-content: flex-start;
}
}
@media (max-width: 860px) {
html,
body {
height: auto;
min-height: 100%;
}
body {
overflow: auto;
grid-template-rows: auto auto;
}
main {
grid-template-columns: 1fr;
grid-template-rows: minmax(360px, 58vh) auto;
}
#stage {
min-height: 360px;
}
.inspector {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.camera-hint {
display: none;
}
}
@media (max-width: 560px) {
.toolbar-controls {
display: grid;
grid-template-columns: 1fr 1fr;
width: 100%;
}
.control {
min-width: 0;
}
.button-row {
grid-column: 1 / -1;
flex-wrap: wrap;
}
.button-row button {
flex: 1 1 auto;
}
.scene-legend {
right: 12px;
max-width: calc(100% - 24px);
}
.histogram-grid {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<header class="toolbar">
<div class="brand">
<span class="brand-mark" aria-hidden="true"></span>
<div>
<strong>Invariant Lab</strong>
<small>Sorting inspection, one checkpoint at a time</small>
</div>
</div>
<div class="toolbar-controls">
<label class="control">
<span>Algorithm</span>
<select id="algorithmSelect" aria-label="Sorting algorithm">
<option value="insertion">Insertion sort</option>
<option value="selection">Selection sort</option>
<option value="bubble">Bubble sort</option>
<option value="merge">Merge sort</option>
<option value="heap">Heap sort</option>
</select>
</label>
<label class="control">
<span>Example data</span>
<select id="datasetSelect" aria-label="Example dataset">
<option value="duplicates">Duplicate-key example</option>
<option value="triple">Three equal keys</option>
<option value="negatives">Negative and duplicate keys</option>
<option value="sorted">Already sorted</option>
<option value="reverse">Reverse sorted</option>
</select>
</label>
<div class="button-row" aria-label="Playback controls">
<button id="resetBtn" type="button" title="Return to the first checkpoint">↺ Reset</button>
<button id="prevBtn" type="button" title="Previous checkpoint">← Back</button>
<button id="nextBtn" type="button" title="Next checkpoint">Next →</button>
<button id="playBtn" type="button" title="Play or pause the checkpoints">▶ Play</button>
<button id="finishBtn" class="primary" type="button" title="Jump to the final state">Final ↗</button>
</div>
<label class="control compact">
<span>Speed</span>
<select id="speedSelect" aria-label="Playback speed">
<option value="1200">Slow</option>
<option value="650" selected>Normal</option>
<option value="250">Fast</option>
</select>
</label>
<button id="cameraBtn" type="button" title="Reset the manually controlled camera">Reset view</button>
</div>
</header>
<main>
<section id="stage" aria-label="Low-poly sorting visualization">
<div id="canvasHost"></div>
<div id="labels" aria-hidden="true"></div>
<div class="scene-hud scene-heading">
<div class="eyebrow">Rendered sorting state</div>
<div id="sceneTitle">Duplicate-key example</div>
<div id="scenePhase">Input</div>
</div>
<div class="scene-hud scene-legend">
<span class="legend-item"><i class="legend-dot established"></i>Invariant region</span>
<span class="legend-item"><i class="legend-dot active"></i>Remaining region</span>
<span class="legend-item">× badge = repeated key</span>
</div>
<div class="scene-hud camera-hint">Drag to orbit · wheel to zoom</div>
</section>
<aside class="inspector" aria-label="Sorting invariant inspector">
<section class="panel">
<div class="step-heading">
<div>
<div class="eyebrow">Current step</div>
<h2 id="stepTitle">Input</h2>
</div>
<div id="stepCounter">1 / 1</div>
</div>
<p id="phaseText">Inspect the current stable checkpoint.</p>
<input id="stepRange" type="range" min="0" max="0" value="0" step="1" aria-label="Sorting checkpoint">
<div class="range-caption"><span>First</span><span>Last</span></div>
<div class="subheading"><span>Rendered sequence</span><span>key · item ID</span></div>
<div id="arrayChips" class="array-chips"></div>
</section>
<section class="panel">
<div class="algorithm-row">
<div id="algorithmName">Insertion sort</div>
<span class="checkpoint-chip">Stable checkpoints</span>
</div>
<p id="algorithmBlurb"></p>
<div class="subheading"><span>Current invariant</span><span>live evidence</span></div>
<p id="invariantText"></p>
<ul id="evidenceList" class="evidence-list"></ul>
</section>
<section class="panel">
<div class="eyebrow">Final verification</div>
<h2>Order, multiset, and identity</h2>
<div id="finalStatus" class="final-status pending" aria-live="polite"></div>
<div id="finalChecks" class="check-list"></div>
<div class="sequence-box">
<span>Expected sorted keys</span>
<code id="expectedSequence"></code>
</div>
<div class="sequence-box">
<span>Keys in the rendered scene</span>
<code id="renderedSequence"></code>
</div>
<div class="histogram-grid">
<div class="histogram-cell">
<span>Input key multiset</span>
<code id="inputHistogram"></code>
</div>
<div class="histogram-cell">
<span>Rendered key multiset</span>
<code id="renderedHistogram"></code>
</div>
</div>
<div id="finalMeta" class="data-note"></div>
</section>
</aside>
</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);
const DATASETS = {
duplicates: {
name: "Duplicate-key example",
keys: [4, 2, 4, 1, 2, 3]
},
triple: {
name: "Three equal keys",
keys: [5, 1, 5, 1, 5, 3]
},
negatives: {
name: "Negative and duplicate keys",
keys: [-3, 2, -1, 2, 0, -3, 4, 1]
},
sorted: {
name: "Already sorted",
keys: [1, 2, 2, 3, 5, 5]
},
reverse: {
name: "Reverse sorted",
keys: [8, 6, 6, 4, 3, 1, 0]
}
};
const algorithmSelect = $("algorithmSelect");
const datasetSelect = $("datasetSelect");
const speedSelect = $("speedSelect");
const resetBtn = $("resetBtn");
const prevBtn = $("prevBtn");
const nextBtn = $("nextBtn");
const playBtn = $("playBtn");
const finishBtn = $("finishBtn");
const cameraBtn = $("cameraBtn");
const stepRange = $("stepRange");
let originalRecords = [];
let timeline = [];
let currentState = null;
let stepIndex = 0;
let playing = false;
let playTimer = null;
function keyHistogram(records) {
const result = new Map();
for (const record of records) {
result.set(record.key, (result.get(record.key) || 0) + 1);
}
return result;
}
function histogramsEqual(a, b) {
if (a.size !== b.size) return false;
for (const [key, count] of a) {
if (b.get(key) !== count) return false;
}
return true;
}
function histogramText(histogram) {
const entries = [...histogram.entries()].sort((a, b) => a[0] - b[0]);
return entries.length
? entries.map(([key, count]) => `${key}×${count}`).join(", ")
: "∅";
}
function stableSorted(records) {
return records.slice().sort((a, b) =>
a.key - b.key || a.originalIndex - b.originalIndex
);
}
function isSorted(records) {
for (let i = 1; i < records.length; i++) {
if (records[i - 1].key > records[i].key) return false;
}
return true;
}
function sameIdSet(actual, expected) {
if (actual.length !== expected.length) return false;
const expectedIds = new Set(expected.map(record => record.id));
return actual.every(record => expectedIds.has(record.id));
}
function sameIdSequence(actual, expected) {
return actual.length === expected.length &&
actual.every((record, index) => record.id === expected[index].id);
}
function sequenceText(records) {
return records.length ? records.map(record => record.key).join(", ") : "∅";
}
function duplicateSummary(records) {
const duplicates = [...keyHistogram(records).entries()]
.filter(([, count]) => count > 1)
.sort((a, b) => a[0] - b[0]);
return duplicates.length
? duplicates.map(([key, count]) => `${key} (×${count})`).join(", ")
: "none";
}
function buildInsertion(input) {
const array = input.slice();
const states = [{
array: array.slice(),
phase: "Input: the sorted prefix is empty",
sortedEnd: -1
}];
for (let i = 1; i < array.length; i++) {
const held = array[i];
let j = i - 1;
let comparisons = 0;
let shifts = 0;
while (j >= 0) {
comparisons++;
if (array[j].key <= held.key) break;
array[j + 1] = array[j];
shifts++;
j--;
}
array[j + 1] = held;
states.push({
array: array.slice(),
phase: `Inserted ${held.id} (key ${held.key}) at index ${j + 1}`,
sortedEnd: i,
insertedId: held.id,
metrics: `${comparisons} comparison${comparisons === 1 ? "" : "s"}, ${shifts} shift${shifts === 1 ? "" : "s"}`
});
}
return states;
}
function assessInsertion(state, original) {
const end = state.sortedEnd;
const shown = state.array;
const prefix = end >= 0 ? shown.slice(0, end + 1) : [];
const suffix = shown.slice(end + 1);
const expectedPrefix = original.slice(0, end + 1);
const expectedSuffix = original.slice(end + 1);
const statement = end < 0
? "Before the first insertion, the empty prefix is sorted and the entire suffix is untouched."
: `After inserting ${state.insertedId}, a[0..${end}] is sorted and has the same key multiset as the original first ${end + 1} records; a[${end + 1}..] is untouched.`;
return {
statement,
evidence: [
{
label: "Sorted prefix",
detail: end < 0
? "The prefix has length 0, so the sortedness condition is vacuously true."
: `[${sequenceText(prefix)}] is nondecreasing.`,
pass: isSorted(prefix)
},
{
label: "Prefix multiset",
detail: end < 0
? "No records have entered the prefix."
: `Rendered ${histogramText(keyHistogram(prefix))} equals original-prefix ${histogramText(keyHistogram(expectedPrefix))}.`,
pass: histogramsEqual(keyHistogram(prefix), keyHistogram(expectedPrefix)) && sameIdSet(prefix, expectedPrefix)
},
{
label: "Untouched suffix",
detail: `Rendered IDs [${suffix.map(record => record.id).join(", ")}] retain their original order.`,
pass: sameIdSequence(suffix, expectedSuffix)
}
]
};
}
function buildSelection(input) {
const array = input.slice();
const states = [{
array: array.slice(),
phase: "Input: the sorted prefix is empty",
sortedEnd: -1
}];
for (let i = 0; i < array.length - 1; i++) {
let minimumIndex = i;
let comparisons = 0;
for (let j = i + 1; j < array.length; j++) {
comparisons++;
if (array[j].key < array[minimumIndex].key) {
minimumIndex = j;
}
}
const selected = array[minimumIndex];
[array[i], array[minimumIndex]] = [array[minimumIndex], array[i]];
states.push({
array: array.slice(),
phase: `Selected ${selected.id} (key ${selected.key}) for position ${i}`,
sortedEnd: i,
metrics: `${comparisons} comparison${comparisons === 1 ? "" : "s"}`
});
}
return states;
}
function assessSelection(state, original) {
const end = state.sortedEnd;
const shown = state.array;
const prefix = end >= 0 ? shown.slice(0, end + 1) : [];
const remainder = shown.slice(end + 1);
const expectedLow = stableSorted(original).slice(0, end + 1);
const expectedHigh = stableSorted(original).slice(end + 1);
const statement = end < 0
? "Before the first pass, the empty prefix is sorted and contains none of the globally smallest keys."
: `After ${end + 1} pass${end === 0 ? "" : "es"}, a[0..${end}] is sorted and contains the ${end + 1} globally smallest keys as a multiset; the suffix contains the rest.`;
return {
statement,
evidence: [
{
label: "Sorted fixed prefix",
detail: `[${sequenceText(prefix)}] is nondecreasing.`,
pass: isSorted(prefix)
},
{
label: "Globally smallest prefix",
detail: `Rendered ${histogramText(keyHistogram(prefix))} equals expected-low ${histogramText(keyHistogram(expectedLow))}.`,
pass: histogramsEqual(keyHistogram(prefix), keyHistogram(expectedLow))
},
{
label: "Remaining multiset",
detail: `Rendered ${histogramText(keyHistogram(remainder))} equals expected-high ${histogramText(keyHistogram(expectedHigh))}.`,
pass: histogramsEqual(keyHistogram(remainder), keyHistogram(expectedHigh))
}
]
};
}
function buildBubble(input) {
const array = input.slice();
const states = [{
array: array.slice(),
phase: "Input: the extracted suffix is empty",
sortedStart: array.length
}];
let pass = 0;
for (let end = array.length - 1; end >= 1; end--) {
let swapped = false;
let comparisons = 0;
let swaps = 0;
for (let j = 0; j < end; j++) {
comparisons++;
if (array[j].key > array[j + 1].key) {
[array[j], array[j + 1]] = [array[j + 1], array[j]];
swapped = true;
swaps++;
}
}
pass++;
states.push({
array: array.slice(),
phase: `Pass ${pass}: the largest active key reached position ${end}`,
sortedStart: end + 1,
earlyExit: !swapped,
metrics: `${comparisons} comparison${comparisons === 1 ? "" : "s"}, ${swaps} swap${swaps === 1 ? "" : "s"}`
});
if (!swapped) break;
}
return states;
}
function assessBubble(state, original) {
const start = state.sortedStart;
const shown = state.array;
const suffix = shown.slice(start);
const active = shown.slice(0, start);
const expectedLarge = stableSorted(original).slice(start);
const expectedSmall = stableSorted(original).slice(0, start);
const statement = state.earlyExit
? `No swap occurred in the active prefix, so it is already sorted. The extracted suffix a[${start}..] is sorted and contains the globally largest keys.`
: `After this pass, the extracted suffix a[${start}..] is sorted and contains the globally largest keys; the active prefix contains exactly the remaining multiset.`;
const evidence = [
{
label: "Sorted extracted suffix",
detail: suffix.length
? `[${sequenceText(suffix)}] is nondecreasing.`
: "The extracted suffix is empty.",
pass: isSorted(suffix)
},
{
label: "Largest-key multiset",
detail: `Rendered ${histogramText(keyHistogram(suffix))} equals expected-large ${histogramText(keyHistogram(expectedLarge))}.`,
pass: histogramsEqual(keyHistogram(suffix), keyHistogram(expectedLarge))
},
{
label: "Active-region multiset",
detail: `Rendered ${histogramText(keyHistogram(active))} equals expected-remainder ${histogramText(keyHistogram(expectedSmall))}.`,
pass: histogramsEqual(keyHistogram(active), keyHistogram(expectedSmall))
}
];
if (state.earlyExit) {
evidence.push({
label: "Early-exit order",
detail: `The active prefix [${sequenceText(active)}] is already nondecreasing.`,
pass: isSorted(active)
});
}
return { statement, evidence };
}
function mergeRange(array, left, middle, right) {
const leftPart = array.slice(left, middle);
const rightPart = array.slice(middle, right);
let i = 0;
let j = 0;
let k = left;
while (i < leftPart.length && j < rightPart.length) {
const chooseLeft =
leftPart[i].key < rightPart[j].key ||
(leftPart[i].key === rightPart[j].key &&
leftPart[i].originalIndex <= rightPart[j].originalIndex);
array[k++] = chooseLeft ? leftPart[i++] : rightPart[j++];
}
while (i < leftPart.length) array[k++] = leftPart[i++];
while (j < rightPart.length) array[k++] = rightPart[j++];
}
function buildMerge(input) {
const array = input.slice();
const states = [{
array: array.slice(),
phase: "Input: every singleton run is sorted",
runs: array.map((_, index) => [index, index + 1])
}];
let level = 0;
for (let width = 1; width < array.length; width *= 2) {
level++;
let merges = 0;
for (let left = 0; left < array.length; left += width * 2) {
const middle = Math.min(left + width, array.length);
const right = Math.min(left + width * 2, array.length);
if (middle < right) {
mergeRange(array, left, middle, right);
merges++;
}
}
const runs = [];
for (let left = 0; left < array.length; left += width * 2) {
runs.push([left, Math.min(left + width * 2, array.length)]);
}
states.push({
array: array.slice(),
phase: `Merge level ${level}: ${runs.length} sorted run${runs.length === 1 ? "" : "s"}`,
runs,
metrics: `${merges} merge${merges === 1 ? "" : "s"}`
});
}
return states;
}
function assessMerge(state, original) {
const shown = state.array;
const runs = state.runs || [[0, shown.length]];
const runDetails = [];
let allSorted = true;
let allMultisetsPreserved = true;
let allIdentitiesPreserved = true;
for (const [left, right] of runs) {
const run = shown.slice(left, right);
const originalBlock = original.slice(left, right);
const runSorted = isSorted(run);
const multisetPreserved = histogramsEqual(
keyHistogram(run),
keyHistogram(originalBlock)
);
const identitiesPreserved = sameIdSet(run, originalBlock);
allSorted = allSorted && runSorted;
allMultisetsPreserved = allMultisetsPreserved && multisetPreserved;
allIdentitiesPreserved = allIdentitiesPreserved && identitiesPreserved;
runDetails.push(
`[${left}..${right - 1}]=[${sequenceText(run)}] ${runSorted ? "sorted" : "not sorted"}`
);
}
return {
statement: "After this merge level, every contiguous run is sorted and contains exactly the records from its corresponding original block.",
evidence: [
{
label: "Every run is sorted",
detail: runDetails.join("; ") + ".",
pass: allSorted
},
{
label: "Run multisets preserved",
detail: "Each rendered run has the same key-frequency histogram as its original block.",
pass: allMultisetsPreserved
},
{
label: "Run identities preserved",
detail: "Each rendered run contains the same unique item IDs as its original block.",
pass: allIdentitiesPreserved
}
]
};
}
function siftDown(array, index, size) {
while (true) {
let largest = index;
const left = index * 2 + 1;
const right = left + 1;
if (left < size && array[left].key > array[largest].key) largest = left;
if (right < size && array[right].key > array[largest].key) largest = right;
if (largest === index) break;
[array[index], array[largest]] = [array[largest], array[index]];
index = largest;
}
}
function heapify(array, size) {
for (let i = Math.floor(size / 2) - 1; i >= 0; i--) {
siftDown(array, i, size);
}
}
function buildHeap(input) {
const array = input.slice();
const states = [{
array: array.slice(),
phase: "Input: heap construction has not run yet",
heapSize: 0,
setup: true
}];
heapify(array, array.length);
states.push({
array: array.slice(),
phase: "Max-heap constructed from the input",
heapSize: array.length
});
for (let end = array.length - 1; end > 0; end--) {
const extracted = array[0];
[array[0], array[end]] = [array[end], array[0]];
siftDown(array, 0, end);
states.push({
array: array.slice(),
phase: `Extracted maximum ${extracted.id} (key ${extracted.key})`,
heapSize: end
});
}
return states;
}
function assessHeap(state, original) {
const shown = state.array;
if (state.setup) {
return {
statement: "Setup state: the original input is intact. The max-heap invariant begins after the heap-construction checkpoint.",
evidence: [
{
label: "Input still intact",
detail: `Rendered keys [${sequenceText(shown)}] match the input key sequence.`,
pass: sameIdSequence(shown, original)
},
{
label: "Input multiset intact",
detail: `Rendered ${histogramText(keyHistogram(shown))} equals input ${histogramText(keyHistogram(original))}.`,
pass: histogramsEqual(keyHistogram(shown), keyHistogram(original))
}
]
};
}
const size = state.heapSize;
const heap = shown.slice(0, size);
const suffix = shown.slice(size);
const expectedSmall = stableSorted(original).slice(0, size);
const expectedLarge = stableSorted(original).slice(size);
let heapProperty = true;
let checkedEdges = 0;
for (let i = 0; i < size; i++) {
const left = i * 2 + 1;
const right = left + 1;
if (left < size) {
checkedEdges++;
if (heap[i].key < heap[left].key) heapProperty = false;
}
if (right < size) {
checkedEdges++;
if (heap[i].key < heap[right].key) heapProperty = false;
}
}
return {
statement: `The prefix a[0..${size - 1}] is a max-heap containing the globally smallest ${size} keys; the suffix a[${size}..] is sorted and contains the globally largest keys.`,
evidence: [
{
label: "Max-heap property",
detail: `Every parent key is ≥ its child keys across ${checkedEdges} checked edge${checkedEdges === 1 ? "" : "s"}.`,
pass: heapProperty
},
{
label: "Heap multiset",
detail: `Heap ${histogramText(keyHistogram(heap))} equals expected-small ${histogramText(keyHistogram(expectedSmall))}.`,
pass: histogramsEqual(keyHistogram(heap), keyHistogram(expectedSmall))
},
{
label: "Extracted suffix",
detail: suffix.length
? `[${sequenceText(suffix)}] is sorted and equals expected-large ${histogramText(keyHistogram(expectedLarge))}.`
: "The extracted suffix is empty.",
pass: isSorted(suffix) && histogramsEqual(keyHistogram(suffix), keyHistogram(expectedLarge))
}
]
};
}
const ALGORITHMS = {
insertion: {
name: "Insertion sort",
blurb: "Insert one record at a time into a growing sorted prefix. Steps are recorded after each completed insertion.",
build: buildInsertion,
assess: assessInsertion
},
selection: {
name: "Selection sort",
blurb: "Repeatedly select the smallest remaining key. Steps are recorded after each completed pass.",
build: buildSelection,
assess: assessSelection
},
bubble: {
name: "Bubble sort",
blurb: "Move the largest active key to the right on each pass. Steps are recorded after each completed pass.",
build: buildBubble,
assess: assessBubble
},
merge: {
name: "Merge sort",
blurb: "Merge adjacent sorted runs in levels. Steps are recorded after each complete merge level.",
build: buildMerge,
assess: assessMerge
},
heap: {
name: "Heap sort",
blurb: "Build a max-heap, then extract its maximum. Steps are recorded after heap construction and each extraction.",
build: buildHeap,
assess: assessHeap
}
};
// ---------- Three.js scene ----------
const stage = $("stage");
const canvasHost = $("canvasHost");
const labelsLayer = $("labels");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08111f);
scene.fog = new THREE.Fog(0x08111f, 16, 31);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 60);
const cameraTarget = new THREE.Vector3(0, 1.25, 0);
let cameraYaw = -0.28;
let cameraPitch = 0.48;
let cameraRadius = 10.5;
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.id = "three-canvas";
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute("aria-label", "Interactive low-poly sorting scene. Drag to orbit and use the wheel to zoom.");
canvasHost.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbddcff, 0x152238, 1.65);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 2.25);
sun.position.set(-4, 9, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -8;
sun.shadow.camera.right = 8;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 25;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x4dd8d0, 0.85);
rimLight.position.set(6, 4, -6);
scene.add(rimLight);
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(6.75, 7.05, 0.5, 12, 1, false),
new THREE.MeshStandardMaterial({
color: 0x15263a,
roughness: 0.92,
metalness: 0.05,
flatShading: true
})
);
platform.position.y = -0.25;
platform.receiveShadow = true;
scene.add(platform);
const platformRing = new THREE.Mesh(
new THREE.TorusGeometry(6.72, 0.045, 4, 32),
new THREE.MeshBasicMaterial({ color: 0x2d6270 })
);
platformRing.rotation.x = Math.PI / 2;
platformRing.position.y = 0.02;
scene.add(platformRing);
const gridPositions = [];
for (let i = -6; i <= 6; i++) {
gridPositions.push(i, 0.012, -6, i, 0.012, 6);
gridPositions.push(-6, 0.012, i, 6, 0.012, i);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute("position", new THREE.Float32BufferAttribute(gridPositions, 3));
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({ color: 0x274056, transparent: true, opacity: 0.42 })
);
scene.add(grid);
const directionArrow = new THREE.Mesh(
new THREE.ConeGeometry(0.15, 0.42, 3),
new THREE.MeshStandardMaterial({
color: 0x62ddcf,
roughness: 0.72,
flatShading: true
})
);
directionArrow.rotation.z = -Math.PI / 2;
directionArrow.position.set(5.3, 0.16, 0);
directionArrow.castShadow = true;
scene.add(directionArrow);
const decorationGeometry = new THREE.ConeGeometry(0.08, 0.24, 3);
const decorationMaterial = new THREE.MeshStandardMaterial({
color: 0x29445d,
roughness: 0.9,
flatShading: true
});
for (let i = 0; i < 12; i++) {
const angle = i / 12 * Math.PI * 2;
const decoration = new THREE.Mesh(decorationGeometry, decorationMaterial);
decoration.position.set(Math.cos(angle) * 6.35, 0.11, Math.sin(angle) * 6.35);
decoration.rotation.y = angle;
scene.add(decoration);
}
const itemGeometry = new THREE.CylinderGeometry(0.34, 0.41, 1, 5, 1, false);
itemGeometry.translate(0, 0.5, 0);
const ringGeometry = new THREE.TorusGeometry(0.51, 0.035, 4, 16);
const padGeometry = new THREE.CylinderGeometry(0.53, 0.58, 0.08, 6);
const padMaterial = new THREE.MeshStandardMaterial({
color: 0x21364c,
roughness: 0.88,
flatShading: true
});
const itemsLayer = new THREE.Group();
const ringsLayer = new THREE.Group();
const padsLayer = new THREE.Group();
scene.add(itemsLayer, ringsLayer, padsLayer);
const itemMap = new Map();
const BASE_Y = 0.08;
function keyColor(key) {
let hue = (key * 0.61803398875) % 1;
if (hue < 0) hue += 1;
return new THREE.Color().setHSL(hue, 0.64, 0.56);
}
function buildSceneItems(records) {
for (const item of itemMap.values()) {
itemsLayer.remove(item.group);
ringsLayer.remove(item.ring);
item.mesh.material.forEach(material => material.dispose());
item.ring.material.dispose();
item.label.remove();
}
itemMap.clear();
while (padsLayer.children.length) padsLayer.remove(padsLayer.children[0]);
const minimum = Math.min(...records.map(record => record.key));
const maximum = Math.max(...records.map(record => record.key));
const span = maximum - minimum || 1;
const spacing = Math.min(1.45, 10.5 / records.length);
const frequencies = keyHistogram(records);
records.forEach((record, index) => {
const x = (index - (records.length - 1) / 2) * spacing;
const height = 0.85 + (record.key - minimum) / span * 2.75;
const color = keyColor(record.key);
const topColor = color.clone().offsetHSL(0, 0.01, 0.12);
const sideMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.68,
metalness: 0.08,
flatShading: true
});
const topMaterial = new THREE.MeshStandardMaterial({
color: topColor,
roughness: 0.56,
metalness: 0.12,
flatShading: true
});
const bottomMaterial = new THREE.MeshStandardMaterial({
color: color.clone().offsetHSL(0, -0.02, -0.11),
roughness: 0.8,
flatShading: true
});
const mesh = new THREE.Mesh(itemGeometry, [
sideMaterial,
topMaterial,
bottomMaterial
]);
mesh.castShadow = true;
mesh.receiveShadow = true;
const group = new THREE.Group();
group.position.set(x, BASE_Y, 0);
group.scale.y = height;
group.add(mesh);
itemsLayer.add(group);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0xf2b866,
transparent: true,
opacity: 0.92,
depthWrite: false
});
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.rotation.x = Math.PI / 2;
ring.position.set(x, BASE_Y + 0.025, 0);
ring.renderOrder = 2;
ringsLayer.add(ring);
const pad = new THREE.Mesh(padGeometry, padMaterial);
pad.position.set(x, 0.04, 0);
pad.receiveShadow = true;
padsLayer.add(pad);
const label = document.createElement("div");
label.className = "bar-label";
const keyElement = document.createElement("strong");
keyElement.textContent = `K${record.key}`;
label.appendChild(keyElement);
const idElement = document.createElement("span");
idElement.className = "item-id";
idElement.textContent = record.id;
label.appendChild(idElement);
if (frequencies.get(record.key) > 1) {
const duplicate = document.createElement("span");
duplicate.className = "duplicate-count";
duplicate.textContent = `×${frequencies.get(record.key)}`;
label.appendChild(duplicate);
}
labelsLayer.appendChild(label);
itemMap.set(record.id, {
group,
mesh,
ring,
label,
targetX: x,
targetHeight: height
});
});
directionArrow.position.x = ((records.length - 1) / 2) * spacing + 0.82;
}
function updateCamera() {
const horizontal = cameraRadius * Math.cos(cameraPitch);
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y + Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z + Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraYaw = -0.28;
cameraPitch = 0.48;
cameraRadius = Math.max(9.2, originalRecords.length * 1.35);
updateCamera();
}
function resizeScene() {
const width = Math.max(1, canvasHost.clientWidth);
const height = Math.max(1, canvasHost.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resizeScene);
resizeObserver.observe(canvasHost);
window.addEventListener("resize", resizeScene);
let drag = null;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
drag = { x: event.clientX, y: event.clientY };
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
renderer.domElement.focus({ preventScroll: true });
});
renderer.domElement.addEventListener("pointermove", event => {
if (!drag) return;
const deltaX = event.clientX - drag.x;
const deltaY = event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
cameraYaw -= deltaX * 0.006;
cameraPitch = THREE.MathUtils.clamp(cameraPitch + deltaY * 0.005, 0.16, 1.12);
updateCamera();
});
function endDrag(event) {
drag = null;
renderer.domElement.classList.remove("dragging");
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("lostpointercapture", () => {
drag = null;
renderer.domElement.classList.remove("dragging");
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
6.2,
20
);
updateCamera();
}, { passive: false });
const projectedLabel = new THREE.Vector3();
function updateLabels() {
const width = canvasHost.clientWidth;
const height = canvasHost.clientHeight;
for (const item of itemMap.values()) {
projectedLabel.set(
item.group.position.x,
BASE_Y + item.group.scale.y + 0.31,
item.group.position.z
).project(camera);
if (projectedLabel.z < -1 || projectedLabel.z > 1) {
item.label.style.display = "none";
continue;
}
const x = (projectedLabel.x * 0.5 + 0.5) * width;
const y = (-projectedLabel.y * 0.5 + 0.5) * height;
item.label.style.display = "flex";
item.label.style.left = `${x}px`;
item.label.style.top = `${y}px`;
}
}
const ESTABLISHED_COLOR = 0x54d8d0;
const ACTIVE_COLOR = 0xf2b866;
const FINAL_COLOR = 0x78e08f;
function updateSceneTargets() {
if (!currentState) return;
const algorithm = algorithmSelect.value;
currentState.array.forEach((record, index) => {
const item = itemMap.get(record.id);
if (!item) return;
const spacing = Math.min(1.45, 10.5 / currentState.array.length);
item.targetX = (index - (currentState.array.length - 1) / 2) * spacing;
let established = false;
if (currentState.isFinal) {
established = true;
} else if (algorithm === "merge") {
established = true;
} else if (algorithm === "insertion" || algorithm === "selection") {
established = index <= currentState.sortedEnd;
} else if (algorithm === "bubble") {
established = index >= currentState.sortedStart;
} else if (algorithm === "heap" && !currentState.setup) {
established = index >= currentState.heapSize;
}
item.ring.material.color.setHex(
currentState.isFinal
? FINAL_COLOR
: established
? ESTABLISHED_COLOR
: ACTIVE_COLOR
);
});
}
// ---------- Inspection UI ----------
function renderDatasetSummary() {
const dataset = DATASETS[datasetSelect.value];
const duplicates = duplicateSummary(originalRecords);
$("sceneTitle").textContent = dataset.name;
$("scenePhase").textContent = currentState ? currentState.phase : "Input";
$("finalMeta").textContent =
`${originalRecords.length} records, ${keyHistogram(originalRecords).size} distinct keys. ` +
`Duplicate keys in this example: ${duplicates}. The final multiset check counts repeated keys by frequency and checks item IDs separately.`;
}
function renderArray() {
const container = $("arrayChips");
container.replaceChildren();
for (const record of currentState.array) {
const chip = document.createElement("span");
chip.className = "array-chip";
const key = document.createElement("span");
key.textContent = record.key;
chip.appendChild(key);
const id = document.createElement("small");
id.textContent = record.id;
chip.appendChild(id);
container.appendChild(chip);
}
}
function renderEvidence() {
const spec = ALGORITHMS[algorithmSelect.value];
const result = spec.assess(currentState, originalRecords);
if (currentState.isFinal) {
result.evidence.push({
label: "Overall rendered order",
detail: `Rendered keys [${sequenceText(currentState.array)}] are nondecreasing.`,
pass: isSorted(currentState.array)
});
}
$("invariantText").textContent = result.statement;
const list = $("evidenceList");
list.replaceChildren();
for (const evidence of result.evidence) {
const row = document.createElement("li");
row.className = "evidence-row";
const icon = document.createElement("span");
icon.className = "evidence-icon";
icon.textContent = evidence.pass ? "✓" : "!";
icon.setAttribute("aria-label", evidence.pass ? "Pass" : "Fail");
row.appendChild(icon);
const copy = document.createElement("div");
const title = document.createElement("span");
title.className = "evidence-title";
title.textContent = evidence.label;
copy.appendChild(title);
const detail = document.createElement("span");
detail.className = "evidence-detail";
detail.textContent = evidence.detail;
copy.appendChild(detail);
row.appendChild(copy);
list.appendChild(row);
}
}
function addCheck(container, kind, title, detail) {
const row = document.createElement("div");
row.className = `check-row ${kind}`;
const mark = document.createElement("span");
mark.className = "check-mark";
mark.textContent = kind === "pass" ? "✓" : kind === "fail" ? "✕" : "→";
row.appendChild(mark);
const copy = document.createElement("div");
const heading = document.createElement("span");
heading.className = "check-title";
heading.textContent = title;
copy.appendChild(heading);
const description = document.createElement("span");
description.className = "check-detail";
description.textContent = detail;
copy.appendChild(description);
row.appendChild(copy);
container.appendChild(row);
}
function renderFinalVerification() {
const status = $("finalStatus");
const checks = $("finalChecks");
checks.replaceChildren();
// These checks deliberately read currentState.array, the same records
// used to position and label the bars in the rendered scene.
const renderedRecords = currentState.array;
const renderedKeys = renderedRecords.map(record => record.key);
const expectedRecords = stableSorted(originalRecords);
const expectedKeys = expectedRecords.map(record => record.key);
const inputHistogram = keyHistogram(originalRecords);
const renderedHistogram = keyHistogram(renderedRecords);
const expectedHistogram = keyHistogram(expectedRecords);
const ordered = isSorted(renderedRecords) &&
renderedKeys.length === expectedKeys.length &&
renderedKeys.every((key, index) => key === expectedKeys[index]);
const multiset = histogramsEqual(inputHistogram, renderedHistogram);
const expectedMultiset = histogramsEqual(inputHistogram, expectedHistogram);
const originalIdentity = new Map(originalRecords.map(record => [record.id, record.key]));
const renderedIdentity = new Map(renderedRecords.map(record => [record.id, record.key]));
const identity = originalIdentity.size === renderedIdentity.size &&
[...originalIdentity.entries()].every(([id, key]) => renderedIdentity.get(id) === key);
$("expectedSequence").textContent = `[${expectedKeys.join(", ")}]`;
$("renderedSequence").textContent = `[${renderedKeys.join(", ")}]`;
$("inputHistogram").textContent = histogramText(inputHistogram);
$("renderedHistogram").textContent = histogramText(renderedHistogram);
status.className = "final-status pending";
const icon = document.createElement("span");
icon.className = "status-icon";
const copy = document.createElement("div");
copy.className = "status-copy";
const title = document.createElement("strong");
const subtitle = document.createElement("span");
copy.append(title, subtitle);
if (!currentState.isFinal) {
icon.textContent = "→";
title.textContent = "Final checkpoint not reached";
subtitle.textContent = "Use Next or Final. The checks below will then read the final array rendered in the scene.";
status.append(icon, copy);
addCheck(
checks,
"pending",
"Live order preview",
`The scene currently renders [${renderedKeys.join(", ")}]. This is not yet the final verification.`
);
return;
}
const allPass = ordered && multiset && expectedMultiset && identity;
status.className = `final-status ${allPass ? "pass" : "fail"}`;
icon.textContent = allPass ? "✓" : "✕";
title.textContent = allPass ? "Final state verified" : "Final verification failed";
subtitle.textContent = allPass
? "Order, duplicate-aware key multiset, and item identities all match the input."
: "At least one final check disagrees with the input.";
status.append(icon, copy);
addCheck(
checks,
ordered ? "pass" : "fail",
"Ordered sequence",
ordered
? `Rendered [${renderedKeys.join(", ")}] exactly matches the expected sorted key sequence; every adjacent comparison is ≤.`
: `Rendered [${renderedKeys.join(", ")}] does not match expected [${expectedKeys.join(", ")}].`
);
addCheck(
checks,
multiset ? "pass" : "fail",
"Unchanged key multiset",
multiset
? `Input ${histogramText(inputHistogram)} = rendered ${histogramText(renderedHistogram)}. Repeated keys are counted by frequency.`
: `Input ${histogramText(inputHistogram)} differs from rendered ${histogramText(renderedHistogram)}.`
);
addCheck(
checks,
expectedMultiset ? "pass" : "fail",
"Expected sorted multiset",
expectedMultiset
? `The expected sorted histogram ${histogramText(expectedHistogram)} agrees with the input histogram.`
: `The expected sorted histogram ${histogramText(expectedHistogram)} disagrees with the input.`
);
addCheck(
checks,
identity ? "pass" : "fail",
"Item identities preserved",
identity
? `All ${originalRecords.length} item IDs still map to their original keys, including both members of each duplicate-key pair.`
: "At least one item ID is missing, duplicated, or mapped to a different key."
);
}
function updatePlaybackButton() {
playBtn.textContent = playing ? "Ⅱ Pause" : "▶ Play";
}
function applyState(index) {
if (!timeline.length) return;
stepIndex = THREE.MathUtils.clamp(index, 0, timeline.length - 1);
currentState = timeline[stepIndex];
stepRange.max = String(timeline.length - 1);
stepRange.value = String(stepIndex);
$("stepCounter").textContent = `${stepIndex + 1} / ${timeline.length}`;
$("stepTitle").textContent = currentState.isFinal
? "Final state"
: stepIndex === 0
? "Input checkpoint"
: `Checkpoint ${stepIndex}`;
const metrics = currentState.metrics ? ` · ${currentState.metrics}` : "";
$("phaseText").textContent = `${currentState.phase}${metrics}.`;
$("scenePhase").textContent = `${currentState.phase}${metrics}`;
prevBtn.disabled = stepIndex === 0;
nextBtn.disabled = currentState.isFinal;
finishBtn.disabled = currentState.isFinal;
const spec = ALGORITHMS[algorithmSelect.value];
$("algorithmName").textContent = spec.name;
$("algorithmBlurb").textContent = spec.blurb;
renderArray();
renderEvidence();
renderFinalVerification();
updateSceneTargets();
}
function rebuildTimeline() {
const spec = ALGORITHMS[algorithmSelect.value];
timeline = spec.build(originalRecords);
timeline.forEach((state, index) => {
state.isFinal = index === timeline.length - 1;
});
applyState(0);
}
function loadDataset() {
stopPlayback();
const dataset = DATASETS[datasetSelect.value];
originalRecords = dataset.keys.map((key, index) => ({
id: `I${index + 1}`,
key,
originalIndex: index
}));
buildSceneItems(originalRecords);
resetCamera();
renderDatasetSummary();
rebuildTimeline();
}
function stopPlayback() {
playing = false;
if (playTimer !== null) clearTimeout(playTimer);
playTimer = null;
updatePlaybackButton();
}
function schedulePlayback() {
if (!playing) return;
playTimer = window.setTimeout(() => {
if (!playing) return;
if (stepIndex >= timeline.length - 1) {
stopPlayback();
return;
}
applyState(stepIndex + 1);
if (currentState.isFinal) {
stopPlayback();
return;
}
schedulePlayback();
}, Number(speedSelect.value));
}
function togglePlayback() {
if (playing) {
stopPlayback();
return;
}
if (currentState.isFinal) applyState(0);
playing = true;
updatePlaybackButton();
schedulePlayback();
}
resetBtn.addEventListener("click", () => {
stopPlayback();
applyState(0);
});
prevBtn.addEventListener("click", () => {
stopPlayback();
applyState(stepIndex - 1);
});
nextBtn.addEventListener("click", () => {
stopPlayback();
applyState(stepIndex + 1);
});
finishBtn.addEventListener("click", () => {
stopPlayback();
applyState(timeline.length - 1);
});
playBtn.addEventListener("click", togglePlayback);
stepRange.addEventListener("input", event => {
stopPlayback();
applyState(Number(event.target.value));
});
speedSelect.addEventListener("change", () => {
if (playing) {
if (playTimer !== null) clearTimeout(playTimer);
schedulePlayback();
}
});
algorithmSelect.addEventListener("change", () => {
stopPlayback();
rebuildTimeline();
});
datasetSelect.addEventListener("change", loadDataset);
cameraBtn.addEventListener("click", resetCamera);
document.addEventListener("keydown", event => {
const tag = document.activeElement?.tagName;
if (["INPUT", "SELECT", "TEXTAREA", "BUTTON"].includes(tag)) return;
if (event.key === "ArrowRight") {
event.preventDefault();
stopPlayback();
applyState(stepIndex + 1);
} else if (event.key === "ArrowLeft") {
event.preventDefault();
stopPlayback();
applyState(stepIndex - 1);
} else if (event.key === "Home") {
event.preventDefault();
stopPlayback();
applyState(0);
} else if (event.key === "End") {
event.preventDefault();
stopPlayback();
applyState(timeline.length - 1);
} else if (event.code === "Space") {
event.preventDefault();
togglePlayback();
}
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const smoothing = 1 - Math.exp(-delta * 10);
const pulse = currentState?.isFinal
? 1 + Math.sin(performance.now() * 0.004) * 0.045
: 1;
for (const item of itemMap.values()) {
item.group.position.x = THREE.MathUtils.lerp(
item.group.position.x,
item.targetX,
smoothing
);
item.group.scale.y = THREE.MathUtils.lerp(
item.group.scale.y,
item.targetHeight,
smoothing
);
item.ring.position.x = item.group.position.x;
item.ring.scale.setScalar(pulse);
}
renderer.render(scene, camera);
updateLabels();
}
resizeScene();
updateCamera();
loadDataset();
animate();
</script>
</body>
</html>
```