// Algorithm Visualizer class AlgorithmVisualizer { constructor() { this.array = []; this.isPlaying = false; this.currentStep = 0; this.animationSpeed = 200; this.algorithmSteps = []; this.initializeElements(); this.generateNewArray(); this.setupEventListeners(); } initializeElements() { this.container = document.getElementById('visualization-container'); this.algorithmSelect = document.getElementById('algorithm-select'); this.algorithmCategory = document.getElementById('algorithm-category'); this.arraySizeInput = document.getElementById('array-size'); this.arraySizeValue = document.getElementById('array-size-value'); this.speedInput = document.getElementById('speed'); this.speedValue = document.getElementById('speed-value'); this.playBtn = document.getElementById('play-btn'); this.pauseBtn = document.getElementById('pause-btn'); this.stepBtn = document.getElementById('step-btn'); this.resetBtn = document.getElementById('reset-btn'); this.generateBtn = document.getElementById('generate-array'); this.pseudocodeElement = document.getElementById('pseudocode'); this.timeComplexity = document.getElementById('time-complexity'); this.spaceComplexity = document.getElementById('space-complexity'); this.algorithmDescription = document.getElementById('algorithm-description'); } setupEventListeners() { this.generateBtn.addEventListener('click', () => this.generateNewArray()); this.arraySizeInput.addEventListener('input', () => { const size = this.arraySizeInput.value; this.arraySizeValue.textContent = size; this.generateNewArray(); }); this.speedInput.addEventListener('input', () => { const speed = this.speedInput.value; this.animationSpeed = 300 - (speed * 25); this.speedValue.textContent = this.getSpeedLabel(speed); }); this.playBtn.addEventListener('click', () => this.play()); this.pauseBtn.addEventListener('click', () => this.pause()); this.stepBtn.addEventListener('click', () => this.step()); this.resetBtn.addEventListener('click', () => this.reset()); this.algorithmSelect.addEventListener('change', () => this.updateAlgorithmInfo()); this.algorithmCategory.addEventListener('change', () => this.updateAlgorithmOptions()); } getSpeedLabel(speed) { const labels = ['Very Slow', 'Slow', 'Medium Slow', 'Medium', 'Medium Fast', 'Fast', 'Very Fast']; return labels[speed - 1] || 'Medium'; } generateNewArray() { const size = parseInt(this.arraySizeInput.value); this.array = Array.from({ length: size }, () => Math.floor(Math.random() * 90) + 10 ); this.renderArray(); this.reset(); // Generate algorithm steps for the current algorithm this.generateAlgorithmSteps(); } renderArray() { this.container.innerHTML = ''; const maxHeight = Math.max(...this.array); this.array.forEach((value, index) => { const bar = document.createElement('div'); bar.className = 'array-bar bg-blue-500 transition-all duration-100'; bar.style.height = `${(value / maxHeight) * 300}px`; bar.style.width = `${Math.max(10, 400 / this.array.length)}px`; bar.dataset.index = index; bar.dataset.value = value; this.container.appendChild(bar); }); } updateAlgorithmOptions() { const category = this.algorithmCategory.value; let options = ''; switch(category) { case 'sorting': options = ` `; break; case 'searching': options = ` `; break; case 'pathfinding': options = ` `; break; case 'recursion': options = ` `; break; } this.algorithmSelect.innerHTML = options; this.updateAlgorithmInfo(); } updateAlgorithmInfo() { const algorithm = this.algorithmSelect.value; const info = this.getAlgorithmInfo(algorithm); this.timeComplexity.textContent = info.timeComplexity; this.spaceComplexity.textContent = info.spaceComplexity; this.algorithmDescription.textContent = info.description; this.pseudocodeElement.textContent = info.pseudocode; } getAlgorithmInfo(algorithm) { const algorithms = { 'bubble-sort': { timeComplexity: 'O(n²)', spaceComplexity: 'O(1)', description: 'Repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.', pseudocode: `for i from 0 to n-1: for j from 0 to n-i-1: if arr[j] > arr[j+1]: swap arr[j] and arr[j+1]` }, 'quick-sort': { timeComplexity: 'O(n log n) average', spaceComplexity: 'O(log n)', description: 'Divide and conquer algorithm that picks an element as pivot and partitions the array.', pseudocode: `function quicksort(arr, low, high): if low < high: pivot = partition(arr, low, high) quicksort(arr, low, pivot-1) quicksort(arr, pivot+1, high)` }, 'merge-sort': { timeComplexity: 'O(n log n)', spaceComplexity: 'O(n)', description: 'Divide and conquer algorithm that divides the array into halves, sorts them, and merges.', pseudocode: `function mergesort(arr): if length(arr) <= 1: return arr mid = length(arr) // 2 left = mergesort(arr[0:mid]) right = mergesort(arr[mid:]) return merge(left, right)` }, 'binary-search': { timeComplexity: 'O(log n)', spaceComplexity: 'O(1)', description: 'Search algorithm that finds the position of a target value within a sorted array.', pseudocode: `function binarySearch(arr, target): low = 0 high = length(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid else if arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1` } }; return algorithms[algorithm] || { timeComplexity: '-', spaceComplexity: '-', description: 'Select an algorithm to see its description', pseudocode: '// Pseudocode will appear here' }; } play() { if (this.isPlaying) return; this.isPlaying = true; this.executeSteps(); } pause() { this.isPlaying = false; } step() { if (this.currentStep < this.algorithmSteps.length) { this.executeStep(this.algorithmSteps[this.currentStep]); this.currentStep++; } } reset() { this.pause(); this.currentStep = 0; this.algorithmSteps = []; this.renderArray(); this.generateAlgorithmSteps(); } executeSteps() { if (!this.isPlaying || this.currentStep >= this.algorithmSteps.length) { this.isPlaying = false; return; } this.executeStep(this.algorithmSteps[this.currentStep]); this.currentStep++; setTimeout(() => { this.executeSteps(); }, this.animationSpeed); } executeStep(step) { const { type, indices, values } = step; const bars = this.container.querySelectorAll('.array-bar'); // Reset all bars to default color bars.forEach(bar => { bar.classList.remove('bg-yellow-500', 'bg-red-500', 'bg-green-500', 'bg-purple-500', 'bg-blue-500'); bar.classList.add('bg-blue-500'); }); switch(type) { case 'compare': indices.forEach(index => { bars[index].classList.remove('bg-blue-500'); bars[index].classList.add('bg-yellow-500'); }); break; case 'swap': const [index1, index2] = indices; this.swapBars(index1, index2); bars[index1].classList.remove('bg-blue-500'); bars[index1].classList.add('bg-red-500'); bars[index2].classList.remove('bg-blue-500'); bars[index2].classList.add('bg-red-500'); break; case 'pivot': bars[indices[0]].classList.remove('bg-blue-500'); bars[indices[0]].classList.add('bg-purple-500'); break; case 'sorted': indices.forEach(index => { bars[index].classList.remove('bg-blue-500'); bars[index].classList.add('bg-green-500'); break; case 'current': bars[indices[0]].classList.remove('bg-blue-500'); bars[indices[0]].classList.add('bg-yellow-500'); break; } } generateAlgorithmSteps() { const algorithm = this.algorithmSelect.value; const array = [...this.array]; this.algorithmSteps = []; switch(algorithm) { case 'bubble-sort': this.generateBubbleSortSteps(array); break; case 'quick-sort': this.generateQuickSortSteps(array, 0, array.length - 1); break; case 'merge-sort': this.generateMergeSortSteps(array, 0, array.length - 1); break; case 'binary-search': this.generateBinarySearchSteps(array, Math.floor(Math.random() * 90) + 10); break; } } generateBubbleSortSteps(array) { const n = array.length; let steps = []; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { // Compare step steps.push({ type: 'compare', indices: [j, j + 1], values: [array[j], array[j + 1]] }); if (array[j] > array[j + 1]) { // Swap step [array[j], array[j + 1]] = [array[j + 1], array[j]]; steps.push({ type: 'swap', indices: [j, j + 1], values: [array[j], array[j + 1]] }); } // Mark as sorted steps.push({ type: 'sorted', indices: [n - i - 1], values: [array[n - i - 1]]] }); } this.algorithmSteps = steps; } generateQuickSortSteps(array, low, high) { if (low < high) { const pivotIndex = this.partitionQuickSort(array, low, high, this.algorithmSteps); this.generateQuickSortSteps(array, low, pivotIndex - 1); this.generateQuickSortSteps(array, pivotIndex + 1, high); } } partititionQuickSort(array, low, high, steps) { const pivot = array[high]; let i = low - 1; // Mark pivot steps.push({ type: 'pivot', indices: [high], values: [pivot] }); for (let j = low; j < high; j++) { // Compare with pivot steps.push({ type: 'compare', indices: [j, high], values: [array[j], pivot] }); if (array[j] <= pivot) { i++; if (i !== j) { // Swap step [array[i], array[j]] = [array[j], array[i]]; steps.push({ type: 'swap', indices: [i, j], values: [array[i], array[j]]] }); } } if (i + 1 !== high) { // Swap pivot to correct position [array[i + 1], array[high]] = [array[high], array[i + 1]]]; steps.push({ type: 'swap', indices: [i + 1, high], values: [array[i + 1], array[high]]] }); } return i + 1; } generateMergeSortSteps(array, left, right) { if (left < right) { const mid = Math.floor((left + right) / 2); this.generateMergeSortSteps(array, left, mid); this.generateMergeSortSteps(array, mid + 1, right); // Merge process would be implemented here } } generateBinarySearchSteps(array, target) { let left = 0; let right = array.length - 1; let steps = []; steps.push({ type: 'current', indices: [left, right], values: [array[left], array[right]]] }); while (left <= right) { const mid = Math.floor((left + right) / 2); // Highlight mid steps.push({ type: 'current', indices: [mid], values: [array[mid]]] }); if (array[mid] === target) { steps.push({ type: 'sorted', indices: [mid], values: [array[mid]]] }); break; } else if (array[mid] < target) { left = mid + 1; } else { right = mid - 1; } steps.push({ type: 'current', indices: [left, right], values: [array[left], array[right]]] }); } this.algorithmSteps = steps; } highlightBars(indices, color = 'bg-yellow-500') { const bars = this.container.querySelectorAll('.array-bar'); bars.forEach(bar => bar.classList.remove('bg-yellow-500', 'bg-red-500', 'bg-green-500', 'bg-purple-500'); indices.forEach(index => { if (bars[index]) { bars[index].classList.add(color); } }); } swapBars(index1, index2) { const bars = this.container.querySelectorAll('.array-bar'); const tempHeight = bars[index1].style.height; bars[index1].style.height = bars[index2].style.height; bars[index2].style.height = tempHeight; // Update data attributes const tempValue = bars[index1].dataset.value; bars[index1].dataset.value = bars[index2].dataset.value; bars[index2].dataset.value = tempValue; } } // Initialize when page loads document.addEventListener('DOMContentLoaded', () => { new AlgorithmVisualizer(); });