// BubbleSortVisualizer.tsx
import React, { useState, useEffect, useRef } from 'react';
import './BubbleSortVisualizer.css'; // Assume this CSS file exists
const DEFAULT_ARRAY_SIZE = 25;
const MIN_DELAY = 50;
const MAX_DELAY = 1000;
// Helper function for creating delay
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const BubbleSortVisualizer: React.FC = () => {
const [array, setArray] = useState<number[]>([]);
const [isSorting, setIsSorting] = useState<boolean>(false);
const [animationSpeed, setAnimationSpeed] = useState<number>(200); // ms
// Ref to store indices currently being compared (optional, for highlighting)
const comparingIndicesRef = useRef<[number, number] | null>(null);
// Ref to store the sorting state/indices to manage the async loop
const sortingStateRef = useRef({ i: 0, j: 0, swapped: false });
// Function to generate a random array
const generateRandomArray = () => {
// Reset sorting state if necessary
setIsSorting(false);
comparingIndicesRef.current = null;
// Generate array (e.g., numbers between 5 and 100, scaled to fit container)
const newArray = Array.from({ length: DEFAULT_ARRAY_SIZE }, () =>
Math.floor(Math.random() * 95) + 5 // Values between 5 and 100
);
setArray(newArray);
};
// Effect to generate array on initial mount
useEffect(() => {
generateRandomArray();
}, []);
// Function to perform the Bubble Sort visualization
const visualizeBubbleSort = async () => {
setIsSorting(true);
comparingIndicesRef.current = null; // Clear highlights initially
let arr = [...array]; // Work on a copy
let n = arr.length;
sortingStateRef.current = { i: 0, j: 0, swapped: false }; // Reset sort state tracker
while (sortingStateRef.current.i < n) {
sortingStateRef.current.swapped = false;
sortingStateRef.current.j = 0;
while (sortingStateRef.current.j < n - 1 - sortingStateRef.current.i) {
let j = sortingStateRef.current.j;
comparingIndicesRef.current = [j, j + 1]; // Highlight indices being compared
await delay(animationSpeed);
if (arr[j] > arr[j + 1]) {
// Swap elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
setArray([...arr]); // Update state to trigger re-render
sortingStateRef.current.swapped = true;
}
sortingStateRef.current.j++;
}
// Optimization: If no swaps in a pass, array is sorted
if (!sortingStateRef.current.swapped) {
break;
}
sortingStateRef.current.i++;
}
comparingIndicesRef.current = null; // Clear comparison highlights
setIsSorting(false);
console.log("Sorting Complete!");
};
const handleStartSort = () => {
if (!isSorting) {
visualizeBubbleSort();
}
};
const handleSpeedChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setAnimationSpeed(parseInt(event.target.value, 10));
};
// --- Rendering Logic ---
return (
<div>
<h1>Bubble Sort Visualizer</h1>
<div className="array-container">
{array.map((value, idx) => {
const isComparing = comparingIndicesRef.current?.includes(idx);
// Add classes for styling based on state
const barClassName = `array-bar ${isComparing ? 'comparing' : ''}`;
return (
<div
key={idx}
className={barClassName}
style={{
height: `${value}%`, // Use value directly as percentage
// CSS will handle width and margin
}}
>
{/* Optionally display value */}
{/* {value} */}
</div>
);
})}
</div>
<div className="controls">
<button onClick={handleStartSort} disabled={isSorting}>
Start Sort
</button>
<button onClick={generateRandomArray} disabled={isSorting}>
New Array
</button>
<label htmlFor="speed-slider">Speed: </label>
<input
id="speed-slider"
type="range"
min={MIN_DELAY}
max={MAX_DELAY}
step="50"
value={animationSpeed}
onChange={handleSpeedChange}
disabled={isSorting}
/>
<span>{animationSpeed} ms</span>
</div>
</div>
);
};
export default BubbleSortVisualizer;