-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
73 lines (61 loc) · 2.45 KB
/
index.php
File metadata and controls
73 lines (61 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
require('vendor/autoload.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bubble Sort Visualization</title>
<style>
/* Add CSS styles for the bars representing the array elements */
.bar {
display: inline-block;
width: 20px;
margin-right: 5px;
background-color: blue;
color: white;
text-align: center;
font-size: 14px;
padding: 5px 0;
}
</style>
</head>
<body>
<div id="visualization"></div>
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function bubbleSortVisualization(arr) {
const visualizationDiv = document.getElementById('visualization');
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
// Visualize the comparison
visualizationDiv.innerHTML = arr.map((value, index) => {
const barHeight = `${value * 20}px`;
const backgroundColor = (index === j || index === j + 1) ? 'red' : 'blue';
return `<div class="bar" style="height: ${barHeight}; background-color: ${backgroundColor}">${value}</div>`;
}).join('');
// Add a delay for visualization
await sleep(100); // Change the sleep time to 250 milliseconds
if (arr[j] > arr[j + 1]) {
// Swap elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
// Final visualization of the sorted array
visualizationDiv.innerHTML = arr.map(value => `<div class="bar" style="height: ${value * 20}px">${value}</div>`).join('');
}
// Example usage with numbers 1 to 9 in random order
const originalArray = Array.from({ length: 9 }, (_, i) => i + 1); // Numbers 1 to 9
for (let i = originalArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[originalArray[i], originalArray[j]] = [originalArray[j], originalArray[i]];
}
bubbleSortVisualization(originalArray.slice());
</script>
</body>
</html>