<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tree vs Array Sort Performance</title>
<style>
body { font-family: sans-serif; padding: 20px; line-height: 1.6; }
.controls { margin-bottom: 20px; }
button { margin-right: 10px; padding: 8px 12px; cursor: pointer; }
#results { background: #f4f4f4; padding: 15px; border-radius: 5px; min-height: 50px; }
</style>
</head>
<body>
<h2>Data Structure Performance Test</h2>
<div class="controls">
<label>Number of Objects:</label>
<input type="number" id="count" value="1000000">
<br><br>
<button onclick="testBST()">1. Random -> BST</button>
<button onclick="testArray(false)">2. Random -> List -> Array -> Sort</button>
<button onclick="testArray(true)">3. Sorted -> List -> Array -> Sort</button>
</div>
<div id="results">Click a button to start...</div>
<script>
const getCount = () => parseInt(document.getElementById('count').value);
const log = (msg) => document.getElementById('results').innerText = msg;
// Simple Iterative BST Node and Insert
function insertBST(root, val) {
let node = { val, left: null, right: null };
if (!root) return node;
let curr = root;
while (true) {
if (val < curr.val) {
if (!curr.left) { curr.left = node; break; }
curr = curr.left;
} else {
if (!curr.right) { curr.right = node; break; }
curr = curr.right;
}
}
return root;
}
function testBST() {
const n = getCount();
log("Generating and inserting...");
setTimeout(() => {
const start = performance.now();
let root = null;
for (let i = 0; i < n; i++) {
root = insertBST(root, Math.random());
}
const end = performance.now();
log(`BST Random Insertion: ${(end - start).toFixed(2)}ms`);
}, 50);
}
function testArray(isSorted) {
const n = getCount();
log("Processing...");
setTimeout(() => {
const start = performance.now();
// 1. Create Linked List (Simulated with simple objects)
let head = { val: Math.random(), next: null };
let curr = head;
for (let i = 1; i < n; i++) {
curr.next = { val: isSorted ? i : Math.random(), next: null };
curr = curr.next;
}
// 2. Transfer to Array
let arr = [];
let temp = head;
while (temp) {
arr.push(temp.val);
temp = temp.next;
}
// 3. Sort
arr.sort((a, b) => a - b);
const end = performance.now();
log(`${isSorted ? 'Sorted' : 'Random'} -> List -> Array -> Sort: ${(end - start).toFixed(2)}ms`);
}, 50);
}
</script>
</body>
</html>