Team Ai
Apppublic

firasx/algorithm-playground

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
sorting.js149 linesDownload Raw Back to algorithms
1// Sorting Visualization Logic2function initSortingVisualization() {3    // Canvas setup4    const canvasContainer = document.getElementById('sorting-animation');5    const canvas = document.createElement('canvas');6    canvas.width = canvasContainer.clientWidth;7    canvas.height = canvasContainer.clientHeight;8    canvasContainer.appendChild(canvas);9    const ctx = canvas.getContext('2d');10    11    // State variables12    let array = [];13    let sorting = false;14    let currentAlgorithm = 'bubble';15    let speed = 5;16    let size = 15;17    18    // Initialize array19    function generateArray() {20        array = [];21        for (let i = 0; i < size; i++) {22            array.push(Math.floor(Math.random() * 100) + 5);23        }24        drawArray();25        resetStats();26    }27    28    // Draw array as bars29    function drawArray(highlight = []) {30        ctx.clearRect(0, 0, canvas.width, canvas.height);31        32        const barWidth = canvas.width / array.length;33        const maxHeight = canvas.height - 20;34        35        for (let i = 0; i < array.length; i++) {36            const barHeight = (array[i] / 105) * maxHeight;37            const x = i * barWidth;38            const y = canvas.height - barHeight;39            40            // Highlight compared elements41            if (highlight.includes(i)) {42                ctx.fillStyle = '#f59e0b';43            } else if (highlight.length > 0) {44                ctx.fillStyle = '#3b82f6';45            } else {46                ctx.fillStyle = '#8b5cf6';47            }48            49            ctx.fillRect(x, y, barWidth - 2, barHeight);50        }51    }52    53    // Reset stats54    function resetStats() {55        document.getElementById('comparisons').textContent = '0';56        document.getElementById('swaps').textContent = '0';57        document.getElementById('time').textContent = '0';58    }59    60    // Update stats61    function updateStats(comparisons, swaps, time) {62        document.getElementById('comparisons').textContent = comparisons;63        document.getElementById('swaps').textContent = swaps;64        document.getElementById('time').textContent = time;65    }66    67    // Bubble Sort implementation with visualization68    async function bubbleSort() {69        let comparisons = 0;70        let swaps = 0;71        const startTime = performance.now();72        73        const len = array.length;74        for (let i = 0; i < len; i++) {75            for (let j = 0; j < len - i - 1; j++) {76                comparisons++;77                78                // Highlight compared elements79                drawArray([j, j + 1]);80                await new Promise(resolve => setTimeout(resolve, 1000 / speed));81                82                if (array[j] > array[j + 1]) {83                    swaps++;84                    [array[j], array[j + 1]] = [array[j + 1], array[j]];85                    drawArray([j, j + 1]);86                    await new Promise(resolve => setTimeout(resolve, 1000 / speed));87                }88                89                updateStats(comparisons, swaps, Math.floor(performance.now() - startTime));90            }91        }92        drawArray();93    }94    95    // Other sorting algorithms would be implemented similarly...96    97    // Event listeners98    document.getElementById('generate-array').addEventListener('click', () => {99        if (!sorting) {100            generateArray();101        }102    });103    104    document.getElementById('start-sort').addEventListener('click', async () => {105        if (!sorting && array.length > 0) {106            sorting = true;107            108            switch(currentAlgorithm) {109                case 'bubble':110                    await bubbleSort();111                    break;112                // Add cases for other algorithms113            }114            115            sorting = false;116        }117    });118    119    document.getElementById('array-size').addEventListener('input', (e) => {120        size = parseInt(e.target.value);121        if (!sorting) {122            generateArray();123        }124    });125    126    document.getElementById('sort-speed').addEventListener('input', (e) => {127        speed = parseInt(e.target.value);128    });129    130    // Algorithm selection131    document.querySelectorAll('.algorithm-btn').forEach(btn => {132        btn.addEventListener('click', () => {133            document.querySelectorAll('.algorithm-btn').forEach(b => b.classList.remove('active'));134            btn.classList.add('active');135            currentAlgorithm = btn.dataset.algo;136            137            // Update explanation based on selected algorithm138            updateAlgorithmExplanation(currentAlgorithm);139        });140    });141    142    function updateAlgorithmExplanation(algorithm) {143        // This would update the explanation section based on the selected algorithm144        // Implementation would include updating text and code examples145    }146    147    // Initial setup148    generateArray();149}