Skip to content

25. Wizualizacja algorytmów sortowania

This content is not available in your language yet.

Animowana wizualizacja sortowania — słupki reprezentujące wartości, kolory oznaczające porównywane elementy, kontrola prędkości animacji.

// Kluczowy trick: algorytm sortowania generuje historię kroków
// a React wyświetla każdy krok po kolei z opóźnieniem
function bubbleSortSteps(arr) {
const steps = [];
const a = [...arr];
for (let i = 0; i < a.length - 1; i++) {
for (let j = 0; j < a.length - 1 - i; j++) {
steps.push({ array: [...a], comparing: [j, j + 1] });
if (a[j] > a[j + 1]) {
[a[j], a[j + 1]] = [a[j + 1], a[j]];
steps.push({ array: [...a], swapped: [j, j + 1] });
}
}
}
steps.push({ array: [...a], done: true });
return steps;
}
function useSortingVisualizer(algorithm) {
const [array, setArray] = useState(generateRandom(30));
const [steps, setSteps] = useState([]);
const [stepIndex, setStepIndex] = useState(0);
const [isPlaying, setIsPlaying] = useState(false);
const [speed, setSpeed] = useState(100);
function startSort() {
const newSteps = algorithm(array);
setSteps(newSteps);
setStepIndex(0);
setIsPlaying(true);
}
useEffect(() => {
if (!isPlaying || stepIndex >= steps.length) { setIsPlaying(false); return; }
const timer = setTimeout(() => {
setArray(steps[stepIndex].array);
setStepIndex((i) => i + 1);
}, speed);
return () => clearTimeout(timer);
}, [isPlaying, stepIndex, steps, speed]);
return { array, isPlaying, speed, setSpeed, startSort };
}
  • Wizualizacja Bubble Sort
  • Słupki SVG lub div z height
  • Podświetlenie porównywanych elementów
  • Kontrola prędkości (wolno / normalnie / szybko)
  • Restart z nową losową tablicą
Ocena: 3.0

Powodzenia!

Wizualizacja sortowania to jeden z najtrudniejszych, ale i najpiękniejszych projektów. Kluczem jest rozdzielenie algorytmu (generuje kroki) od wizualizacji (odtwarza kroki). NIE animuj bezpośrednio w algorytmie sortowania — wygeneruj całą historię kroków z góry, a potem odtwarzaj ją krok po kroku w React!