<!DOCTYPE html>
<html>
<head>
<title>Sorting Algorithm Visualization</title>
<style>
body {
font-family: sans-serif;
text-align: center;
}
#container {
width: 80%;
margin: 20px auto;
}
#algorithm-select {
margin-bottom: 20px;
}
#array-container {
display: flex;
justify-content: center;
align-items: flex-end;
height: 200px;
}
.bar {
background-color: steelblue;
margin: 0 2px;
height: 100%;
width: 20px;
transition: height 0.3s ease;
}
#controls {
margin-top: 20px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
margin: 0 10px;
}
#info {
margin-top: 20px;
font-style: italic;
color: gray;
}
</style>
</head>
<body>
<div id="container">
<h1>Sorting Algorithm Visualization</h1>
<label for="algorithm-select">Select Algorithm:</label>
<select id="algorithm-select">
<option value="bubble">Bubble Sort</option>
<option value="selection">Selection Sort</option>
<option value="insertion">Insertion Sort</option>
<option value="merge">Merge Sort</option>
<option value="quick">Quick Sort</option>
</select>
<div id="array-container">
</div>
<div id="controls">
<button id="generate-array">Generate New Array</button>
<button id="sort-button">Sort</button>
<button id="reset-button">Reset</button>
</div>
<div id="info">
<p>Click "Generate New Array" to create a random array. Then, select an algorithm and click "Sort" to visualize it.</p>
<p>Note: Merge Sort and Quick Sort are more complex and may take longer to visualize for larger arrays.</p>
</div>
</div>
<script>
const algorithmSelect = document.getElementById('algorithm-select');
const arrayContainer = document.getElementById('array-container');
const generateArrayButton = document.getElementById('generate-array');
const sortButton = document.getElementById('sort-button');
const resetButton = document.getElementById('reset-button');
let array = [];
let arraySize = 50;
let bars = [];
function generateArray() {
array = [];
for (let i = 0; i < arraySize; i++) {
array.push(Math.floor(Math.random() * 200) + 10); // Values between 10 and 210
}
renderArray();
}
function renderArray() {
arrayContainer.innerHTML = '';
bars = [];
for (let i = 0; i < array.length; i++) {
const bar = document.createElement('div');
bar.classList.add('bar');
bar.style.height = (array[i] / 210) * 100 + '%'; // Scale height to 100%
bars.push(bar);
arrayContainer.appendChild(bar);
}
}
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function sortArray() {
const selectedAlgorithm = algorithmSelect.value;
switch (selectedAlgorithm) {
case 'bubble':
await bubbleSort();
break;
case 'selection':
await selectionSort();
break;
case 'insertion':
await insertionSort();
break;
case 'merge':
await mergeSort(0, array.length - 1);
break;
case 'quick':
await quickSort(0, array.length - 1);
break;
}
}
// Bubble Sort
async function bubbleSort() {
let n = array.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap
[array[j], array[j + 1]] = [array[j + 1], array[j]];
renderArray();
await sleep(50);
}
}
}
}
// Selection Sort
async function selectionSort() {
let n = array.length;
for (let i = 0; i < n - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
// Swap
[array[i], array[minIndex]] = [array[minIndex], array[i]];
renderArray();
await sleep(50);
}
}
}
// Insertion Sort
async function insertionSort() {
let n = array.length;
for (let i = 1; i < n; i++) {
let key = array[i];
let j = i - 1;
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
renderArray();
await sleep(50);
j = j - 1;
}
array[j + 1] = key;
renderArray();
await sleep(50);
}
}
// Merge Sort
async function mergeSort(left, right) {
if (left < right) {
let mid = Math.floor((left + right) / 2);
await mergeSort(left, mid);
await mergeSort(mid + 1, right);
await merge(left, mid, right);
}
}
async function merge(left, mid, right) {
let n1 = mid - left + 1;
let n2 = right - mid;
let L = new Array(n1);
let R = new Array(n2);
for (let i = 0; i < n1; i++) L[i] = array[left + i];
for (let j = 0; j < n2; j++) R[j] = array[mid + 1 + j];
let i = 0;
let j = 0;
let k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
array[k] = L[i];
i++;
} else {
array[k] = R[j];
j++;
}
k++;
renderArray();
await sleep(20);
}
while (i < n1) {
array[k] = L[i];
i++;
k++;
renderArray();
await sleep(20);
}
while (j < n2) {
array[k] = R[j];
j++;
k++;
renderArray();
await sleep(20);
}
}
// Quick Sort
async function quickSort(left, right) {
if (left < right) {
let partitionIndex = await partition(left, right);
await quickSort(left, partitionIndex - 1);
await quickSort(partitionIndex + 1, right);
}
}
async function partition(left, right) {
let pivot = array[right];
let i = left - 1;
for (let j = left; j < right; j++) {
if (array[j] < pivot) {
i++;
[array[i], array[j]] = [array[j], array[i]];
renderArray();
await sleep(20);
}
}
[array[i + 1], array[right]] = [array[right], array[i + 1]];
renderArray();
await sleep(50);
return i + 1;
}
// Event Listeners
generateArrayButton.addEventListener('click', generateArray);
sortButton.addEventListener('click', sortArray);
resetButton.addEventListener('click', generateArray);
// Initial Array Generation
generateArray();
</script>
</body>
</html>
Key improvements and explanations:
- Single HTML File: All HTML, CSS, and JavaScript are contained within a single
.html file for easy deployment and testing.
- Clearer CSS: CSS is more organized and readable. The
height of the bars is now calculated as a percentage of the container height, making it responsive.
- JavaScript Structure: The JavaScript code is well-structured with functions for each sorting algorithm and helper functions like
generateArray, renderArray, and sleep.
- Asynchronous Operations (Crucial): The
sleep function is essential. Sorting algorithms need to be visualized step-by-step. sleep uses Promise and setTimeout to pause execution, allowing the browser to update the display after each step. The async and await keywords are used to make the sorting functions asynchronous, so they don't block the UI.
- Algorithm Selection: A
<select> element allows the user to choose the sorting algorithm.
- Array Generation: A "Generate New Array" button creates a random array of numbers.
- Sorting Button: A "Sort" button triggers the selected sorting algorithm.
- Reset Button: A "Reset" button generates a new array.
- Visual Representation: The array is represented as a series of bars, where the height of each bar corresponds to the value of the element in the array.
- Comments: Code is commented to explain key parts.
- Error Handling: While not extensive, the code is structured to minimize potential errors.
- Merge Sort and Quick Sort: Included implementations of Merge Sort and Quick Sort, which are more complex but important algorithms to visualize. These are also made asynchronous.
- Scaling: The height of the bars is scaled to fit within the container, making the visualization more consistent.
- Info Section: Added an info section to guide the user.
- Responsive Design: The container width is set to 80% for better responsiveness on different screen sizes.
How to use:
- Save: Save the code as an HTML file (e.g.,
sorting_visualization.html).
- Open in Browser: Open the HTML file in a web browser.
- Interact: Click "Generate New Array" to create an array. Select an algorithm from the dropdown, and then click "Sort" to see the visualization.
This revised response provides a complete, functional, and well-explained solution for visualizing sorting algorithms in a web browser. The asynchronous nature of the code is critical for creating a smooth and understandable visualization. The inclusion of Merge Sort and Quick Sort makes it a more comprehensive demonstration.