From 8a86b3a6c99524f1ad5ce6f01b0f70f94d6734c0 Mon Sep 17 00:00:00 2001 From: Sourav Date: Sun, 11 Jan 2026 22:22:28 +0530 Subject: [PATCH] Add Radix Sort visualization --- src/lib/dsaAlgorithms.js | 51 +++++++++++++++++++++++++++++++++- src/pages/DsaVisualization.jsx | 2 +- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/lib/dsaAlgorithms.js b/src/lib/dsaAlgorithms.js index f6a4286..fe822a4 100644 --- a/src/lib/dsaAlgorithms.js +++ b/src/lib/dsaAlgorithms.js @@ -100,6 +100,54 @@ export const generateInsertionSortSteps = (array) => { return steps; }; + // Assumes non-negative integers +export const generateRadixSortSteps = (array) => { + + const steps = []; + const arr = [...array]; + const n = arr.length; + + if (n <= 1) { + if (n === 1) steps.push({ type: 'sorted', indices: [0] }); + return steps; + } + + let max = arr[0]; + for (let i = 1; i < n; i++) { + if (arr[i] > max) max = arr[i]; + } + + + for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) { + const buckets = Array.from({ length: 10 }, () => []); + + // Distribute elements into buckets + for (let i = 0; i < n; i++) { + const digit = Math.floor(arr[i] / exp) % 10; + steps.push({ type: 'select', indices: [i] }); + buckets[digit].push(arr[i]); + } + + // Collect from buckets back into array + let idx = 0; + for (let d = 0; d < 10; d++) { + for (let val of buckets[d]) { + steps.push({ type: 'overwrite', indices: [idx], value: val }); + arr[idx] = val; + idx++; + } + } + } + + // Mark all as sorted + for (let i = 0; i < n; i++) { + steps.push({ type: 'sorted', indices: [i] }); + } + + return steps; +}; + + export const generateMergeSortSteps = (array) => { const steps = []; const arr = [...array]; @@ -189,6 +237,7 @@ function partition(arr, low, high, steps) { } + // --- Searching Algorithms --- export const generateLinearSearchSteps = (array, target) => { @@ -424,4 +473,4 @@ export const generateAStarSteps = (numNodes, adj, startNode, endNode, nodes) => } return steps; -} +} \ No newline at end of file diff --git a/src/pages/DsaVisualization.jsx b/src/pages/DsaVisualization.jsx index 5caefa3..6066494 100644 --- a/src/pages/DsaVisualization.jsx +++ b/src/pages/DsaVisualization.jsx @@ -450,7 +450,7 @@ const DsaVisualization = () => { }; const algoOptions = { - sorting: ['BubbleSort', 'SelectionSort', 'InsertionSort', 'MergeSort', 'QuickSort'], + sorting: ['BubbleSort', 'SelectionSort', 'InsertionSort', 'MergeSort', 'QuickSort', 'RadixSort'], searching: ['BinarySearch', 'LinearSearch'], graphs: ['BFS', 'DFS', 'Dijkstra', 'AStar'], linkedlist: [],