0% found this document useful (0 votes)
8 views23 pages

Array Sorting Visualizer Component

The document contains TypeScript components for visualizing sorting algorithms, including ArrayVisualizer, CodeDisplay, and VisualizerControls. It defines interfaces for algorithm steps and list items, and provides implementations for bubble, selection, insertion, quick, and merge sort algorithms. Each component is designed to display the sorting process interactively, allowing users to change algorithms, adjust array sizes, and control the visualization speed.

Uploaded by

mahi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views23 pages

Array Sorting Visualizer Component

The document contains TypeScript components for visualizing sorting algorithms, including ArrayVisualizer, CodeDisplay, and VisualizerControls. It defines interfaces for algorithm steps and list items, and provides implementations for bubble, selection, insertion, quick, and merge sort algorithms. Each component is designed to display the sorting process interactively, allowing users to change algorithms, adjust array sizes, and control the visualization speed.

Uploaded by

mahi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ArrayVisualiser.

tsx

import { AlgorithmStep } from '../types/visualizer';

interface ArrayVisualizerProps {
step: AlgorithmStep;
}

export const ArrayVisualizer = ({ step }: ArrayVisualizerProps) => {


const maxValue = [Link](...[Link](item => [Link]));

return (
<div className="bg-white rounded-lg shadow-lg p-6">
<div className="mb-6">
<h3 className="text-lg font-semibold text-gray-800 mb-2">
Array Visualization
</h3>
<p className="text-sm text-gray-600">{[Link]}</p>
</div>

<div className="flex items-end justify-center gap-2 h-80 mb-6">


{[Link]((item, index) => {
const isComparing = [Link]?.includes(index);
const isSwapping = [Link]?.includes(index);
const isSorted = [Link]?.includes(index);

let barColor = [Link];


if (isSorted) barColor = '#10b981';
else if (isSwapping) barColor = '#ef4444';
else if (isComparing) barColor = '#f59e0b';

const height = ([Link] / maxValue) * 100;

return (
<div
key={[Link]}
className="flex flex-col items-center flex-1 transition-all
duration-300"
>
<div
className="w-full rounded-t-lg transition-all duration-300
relative"
style={{
height: `${height}%`,
backgroundColor: barColor,
minHeight: '40px'
}}
>
<span className="absolute inset-0 flex items-center justify-
center text-white font-semibold text-xs">
{[Link]}
</span>
</div>
<div className="text-xs text-gray-500 mt-2">{index}</div>
</div>
);
})}
</div>

<div className="flex gap-4 text-sm">


<div className="flex items-center gap-2">
<div className="w-4 h-4 rounded" style={{ backgroundColor:
'#f59e0b' }}></div>
<span>Comparing</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-4 rounded" style={{ backgroundColor:
'#ef4444' }}></div>
<span>Swapping</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-4 rounded" style={{ backgroundColor:
'#10b981' }}></div>
<span>Sorted</span>
</div>
</div>
</div>
);
};

[Link]

import { SortAlgorithm } from '../types/visualizer';

interface CodeDisplayProps {
algorithm: SortAlgorithm;
}

const codeExamples: Record<SortAlgorithm, { code: string; complexity:


string }> = {
bubble: {
code: `function bubbleSort(arr) {
for (let i = 0; i < [Link] - 1; i++) {
for (let j = 0; j < [Link] - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}`,
complexity: 'Time: O(n²) | Space: O(1)'
},
selection: {
code: `function selectionSort(arr) {
for (let i = 0; i < [Link] - 1; i++) {
let minIdx = i;
for (let j = i + 1; j < [Link]; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
if (minIdx !== i) {
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
}
}
return arr;
}`,
complexity: 'Time: O(n²) | Space: O(1)'
},
insertion: {
code: `function insertionSort(arr) {
for (let i = 1; i < [Link]; i++) {
let key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}`,
complexity: 'Time: O(n²) | Space: O(1)'
},
quick: {
code: `function quickSort(arr, low = 0, high = [Link] - 1) {
if (low < high) {
const pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
return arr;
}
function partition(arr, low, high) {
const pivot = arr[high];
let i = low - 1;
for (let j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1;
}`,
complexity: 'Time: O(n log n) avg | Space: O(log n)'
},
merge: {
code: `function mergeSort(arr, left = 0, right = [Link] - 1) {
if (left < right) {
const mid = [Link]((left + right) / 2);
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
return arr;
}

function merge(arr, left, mid, right) {


const leftArr = [Link](left, mid + 1);
const rightArr = [Link](mid + 1, right + 1);
let i = 0, j = 0, k = left;

while (i < [Link] && j < [Link]) {


arr[k++] = leftArr[i] <= rightArr[j] ?
leftArr[i++] : rightArr[j++];
}
while (i < [Link]) arr[k++] = leftArr[i++];
while (j < [Link]) arr[k++] = rightArr[j++];
}`,
complexity: 'Time: O(n log n) | Space: O(n)'
}
};

export const CodeDisplay = ({ algorithm }: CodeDisplayProps) => {


const { code, complexity } = codeExamples[algorithm];

return (
<div className="bg-white rounded-lg shadow-lg p-6">
<div className="mb-4">
<h3 className="text-lg font-semibold text-gray-800 mb-2">
{[Link](0).toUpperCase() + [Link](1)} Sort
Implementation
</h3>
<p className="text-sm text-gray-600">{complexity}</p>
</div>

<div className="bg-gray-900 rounded-lg p-4 overflow-x-auto">


<pre className="text-sm text-green-400 font-mono">
<code>{code}</code>
</pre>
</div>
</div>
);
};

[Link]

import { SortAlgorithm } from '../types/visualizer';


import { Play, Pause, RotateCcw, SkipForward, SkipBack } from 'lucide-
react';

interface VisualizerControlsProps {
algorithm: SortAlgorithm;
onAlgorithmChange: (algorithm: SortAlgorithm) => void;
arraySize: number;
onArraySizeChange: (size: number) => void;
speed: number;
onSpeedChange: (speed: number) => void;
isPlaying: boolean;
onPlayPause: () => void;
onReset: () => void;
onStepForward: () => void;
onStepBackward: () => void;
currentStep: number;
totalSteps: number;
}

export const VisualizerControls = ({


algorithm,
onAlgorithmChange,
arraySize,
onArraySizeChange,
speed,
onSpeedChange,
isPlaying,
onPlayPause,
onReset,
onStepForward,
onStepBackward,
currentStep,
totalSteps,
}: VisualizerControlsProps) => {
return (
<div className="bg-white rounded-lg shadow-lg p-6 space-y-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-
2">
Algorithm
</label>
<select
value={algorithm}
onChange={(e) => onAlgorithmChange([Link] as
SortAlgorithm)}
className="w-full px-4 py-2 border border-gray-300 rounded-lg
focus:ring-2 focus:ring-blue-500 focus:border-transparent"
disabled={isPlaying}
>
<option value="bubble">Bubble Sort</option>
<option value="selection">Selection Sort</option>
<option value="insertion">Insertion Sort</option>
<option value="quick">Quick Sort</option>
<option value="merge">Merge Sort</option>
</select>
</div>

<div>
<label className="block text-sm font-medium text-gray-700 mb-
2">
Array Size: {arraySize}
</label>
<input
type="range"
min="5"
max="20"
value={arraySize}
onChange={(e) => onArraySizeChange(Number([Link]))}
className="w-full"
disabled={isPlaying}
/>
</div>

<div>
<label className="block text-sm font-medium text-gray-700 mb-
2">
Speed: {speed}ms
</label>
<input
type="range"
min="100"
max="2000"
step="100"
value={speed}
onChange={(e) => onSpeedChange(Number([Link]))}
className="w-full"
/>
</div>

<div className="flex gap-2">


<button
onClick={onStepBackward}
disabled={currentStep === 0 || isPlaying}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2
bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300
disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
<SkipBack size={20} />
</button>

<button
onClick={onPlayPause}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2
bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
>
{isPlaying ? <Pause size={20} /> : <Play size={20} />}
{isPlaying ? 'Pause' : 'Play'}
</button>

<button
onClick={onStepForward}
disabled={currentStep >= totalSteps - 1 || isPlaying}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2
bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300
disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
<SkipForward size={20} />
</button>
</div>

<button
onClick={onReset}
disabled={isPlaying}
className="w-full flex items-center justify-center gap-2 px-4 py-2
bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-
50 disabled:cursor-not-allowed transition-colors"
>
<RotateCcw size={20} />
Reset & Generate New
</button>

<div className="pt-4 border-t border-gray-200">


<div className="text-sm text-gray-600">
Step {currentStep + 1} of {totalSteps}
</div>
</div>
</div>
);
};

[Link]

export interface ListItem {


id: string;
value: number;
color: string;
}

export interface AlgorithmStep {


array: ListItem[];
comparing?: number[];
swapping?: number[];
sorted?: number[];
message: string;
}

export type SortAlgorithm = 'bubble' | 'selection' | 'insertion' | 'quick' |


'merge';

SortingAlgorithms:

import { ListItem, AlgorithmStep } from '../types/visualizer';

const generateColor = () => {


const colors = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6',
'#ec4899'];
return colors[[Link]([Link]() * [Link])];
};

export const bubbleSort = (arr: ListItem[]): AlgorithmStep[] => {


const steps: AlgorithmStep[] = [];
const array = [Link](item => ({ ...item }));

[Link]({
array: [Link](item => ({ ...item })),
message: 'Starting Bubble Sort: Compare adjacent elements and swap
if needed'
});

for (let i = 0; i < [Link] - 1; i++) {


for (let j = 0; j < [Link] - i - 1; j++) {
[Link]({
array: [Link](item => ({ ...item })),
comparing: [j, j + 1],
message: `Comparing elements at index ${j} (${array[j].value}) and
${j + 1} (${array[j + 1].value})`
});

if (array[j].value > array[j + 1].value) {


[array[j], array[j + 1]] = [array[j + 1], array[j]];

[Link]({
array: [Link](item => ({ ...item })),
swapping: [j, j + 1],
message: `Swapping elements at index ${j} and ${j + 1}`
});
}
}
}

[Link]({
array: [Link](item => ({ ...item })),
sorted: [Link]((_, idx) => idx),
message: 'Bubble Sort Complete!'
});

return steps;
};

export const selectionSort = (arr: ListItem[]): AlgorithmStep[] => {


const steps: AlgorithmStep[] = [];
const array = [Link](item => ({ ...item }));

[Link]({
array: [Link](item => ({ ...item })),
message: 'Starting Selection Sort: Find minimum element and move to
sorted portion'
});

for (let i = 0; i < [Link] - 1; i++) {


let minIdx = i;

for (let j = i + 1; j < [Link]; j++) {


[Link]({
array: [Link](item => ({ ...item })),
comparing: [minIdx, j],
sorted: [Link]({ length: i }, (_, k) => k),
message: `Finding minimum: comparing ${array[minIdx].value} with
${array[j].value}`
});

if (array[j].value < array[minIdx].value) {


minIdx = j;
}
}

if (minIdx !== i) {
[array[i], array[minIdx]] = [array[minIdx], array[i]];

[Link]({
array: [Link](item => ({ ...item })),
swapping: [i, minIdx],
sorted: [Link]({ length: i }, (_, k) => k),
message: `Swapping minimum element to position ${i}`
});
}
}

[Link]({
array: [Link](item => ({ ...item })),
sorted: [Link]((_, idx) => idx),
message: 'Selection Sort Complete!'
});

return steps;
};

export const insertionSort = (arr: ListItem[]): AlgorithmStep[] => {


const steps: AlgorithmStep[] = [];
const array = [Link](item => ({ ...item }));

[Link]({
array: [Link](item => ({ ...item })),
message: 'Starting Insertion Sort: Insert each element into its correct
position'
});

for (let i = 1; i < [Link]; i++) {


const key = array[i];
let j = i - 1;

[Link]({
array: [Link](item => ({ ...item })),
comparing: [i],
sorted: [Link]({ length: i }, (_, k) => k),
message: `Inserting element ${[Link]} into sorted portion`
});

while (j >= 0 && array[j].value > [Link]) {


[Link]({
array: [Link](item => ({ ...item })),
comparing: [j, j + 1],
message: `Shifting ${array[j].value} to the right`
});

array[j + 1] = array[j];
j--;
}

array[j + 1] = key;

[Link]({
array: [Link](item => ({ ...item })),
sorted: [Link]({ length: i + 1 }, (_, k) => k),
message: `Inserted ${[Link]} at position ${j + 1}`
});
}

[Link]({
array: [Link](item => ({ ...item })),
sorted: [Link]((_, idx) => idx),
message: 'Insertion Sort Complete!'
});

return steps;
};

export const quickSort = (arr: ListItem[]): AlgorithmStep[] => {


const steps: AlgorithmStep[] = [];
const array = [Link](item => ({ ...item }));

[Link]({
array: [Link](item => ({ ...item })),
message: 'Starting Quick Sort: Partition around pivot and recursively
sort'
});

const partition = (low: number, high: number): number => {


const pivot = array[high];

[Link]({
array: [Link](item => ({ ...item })),
comparing: [high],
message: `Choosing pivot: ${[Link]} at index ${high}`
});

let i = low - 1;

for (let j = low; j < high; j++) {


[Link]({
array: [Link](item => ({ ...item })),
comparing: [j, high],
message: `Comparing ${array[j].value} with pivot ${[Link]}`
});

if (array[j].value < [Link]) {


i++;
if (i !== j) {
[array[i], array[j]] = [array[j], array[i]];

[Link]({
array: [Link](item => ({ ...item })),
swapping: [i, j],
message: `Swapping ${array[i].value} and ${array[j].value}`
});
}
}
}

[array[i + 1], array[high]] = [array[high], array[i + 1]];

[Link]({
array: [Link](item => ({ ...item })),
swapping: [i + 1, high],
message: `Placing pivot ${[Link]} at position ${i + 1}`
});

return i + 1;
};

const quickSortRecursive = (low: number, high: number) => {


if (low < high) {
const pi = partition(low, high);
quickSortRecursive(low, pi - 1);
quickSortRecursive(pi + 1, high);
}
};

quickSortRecursive(0, [Link] - 1);

[Link]({
array: [Link](item => ({ ...item })),
sorted: [Link]((_, idx) => idx),
message: 'Quick Sort Complete!'
});

return steps;
};

export const mergeSort = (arr: ListItem[]): AlgorithmStep[] => {


const steps: AlgorithmStep[] = [];
const array = [Link](item => ({ ...item }));

[Link]({
array: [Link](item => ({ ...item })),
message: 'Starting Merge Sort: Divide array and merge sorted halves'
});

const merge = (left: number, mid: number, right: number) => {


const leftArray = [Link](left, mid + 1);
const rightArray = [Link](mid + 1, right + 1);

[Link]({
array: [Link](item => ({ ...item })),
comparing: [Link]({ length: right - left + 1 }, (_, i) => left + i),
message: `Merging subarrays from index ${left} to ${right}`
});

let i = 0, j = 0, k = left;

while (i < [Link] && j < [Link]) {


if (leftArray[i].value <= rightArray[j].value) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}

while (i < [Link]) {


array[k] = leftArray[i];
i++;
k++;
}

while (j < [Link]) {


array[k] = rightArray[j];
j++;
k++;
}
[Link]({
array: [Link](item => ({ ...item })),
message: `Merged subarray from ${left} to ${right}`
});
};

const mergeSortRecursive = (left: number, right: number) => {


if (left < right) {
const mid = [Link]((left + right) / 2);

[Link]({
array: [Link](item => ({ ...item })),
comparing: [Link]({ length: right - left + 1 }, (_, i) => left + i),
message: `Dividing array from ${left} to ${right}`
});

mergeSortRecursive(left, mid);
mergeSortRecursive(mid + 1, right);
merge(left, mid, right);
}
};

mergeSortRecursive(0, [Link] - 1);

[Link]({
array: [Link](item => ({ ...item })),
sorted: [Link]((_, idx) => idx),
message: 'Merge Sort Complete!'
});

return steps;
};

export const generateRandomArray = (size: number): ListItem[] => {


return [Link]({ length: size }, (_, i) => ({
id: `item-${i}-${[Link]()}`,
value: [Link]([Link]() * 100) + 1,
color: generateColor()
}));
};

[Link]
import { useState, useEffect, useCallback } from 'react';
import { ListItem, SortAlgorithm, AlgorithmStep } from './types/visualizer';
import {
generateRandomArray,
bubbleSort,
selectionSort,
insertionSort,
quickSort,
mergeSort
} from './utils/sortingAlgorithms';
import { VisualizerControls } from './components/VisualizerControls';
import { ArrayVisualizer } from './components/ArrayVisualizer';
import { CodeDisplay } from './components/CodeDisplay';
import { Code2 } from 'lucide-react';

function App() {
const [algorithm, setAlgorithm] = useState<SortAlgorithm>('bubble');
const [arraySize, setArraySize] = useState(10);
const [speed, setSpeed] = useState(500);
const [array, setArray] = useState<ListItem[]>([]);
const [steps, setSteps] = useState<AlgorithmStep[]>([]);
const [currentStep, setCurrentStep] = useState(0);
const [isPlaying, setIsPlaying] = useState(false);

const generateSteps = useCallback((arr: ListItem[], algo: SortAlgorithm)


=> {
switch (algo) {
case 'bubble':
return bubbleSort(arr);
case 'selection':
return selectionSort(arr);
case 'insertion':
return insertionSort(arr);
case 'quick':
return quickSort(arr);
case 'merge':
return mergeSort(arr);
default:
return bubbleSort(arr);
}
}, []);

const initializeArray = useCallback(() => {


const newArray = generateRandomArray(arraySize);
setArray(newArray);
const newSteps = generateSteps(newArray, algorithm);
setSteps(newSteps);
setCurrentStep(0);
setIsPlaying(false);
}, [arraySize, algorithm, generateSteps]);

useEffect(() => {
initializeArray();
}, [initializeArray]);
useEffect(() => {
if (isPlaying && currentStep < [Link] - 1) {
const timer = setTimeout(() => {
setCurrentStep(prev => prev + 1);
}, speed);
return () => clearTimeout(timer);
} else if (currentStep >= [Link] - 1) {
setIsPlaying(false);
}
}, [isPlaying, currentStep, [Link], speed]);

const handlePlayPause = () => {


if (currentStep >= [Link] - 1) {
setCurrentStep(0);
}
setIsPlaying(!isPlaying);
};

const handleReset = () => {


initializeArray();
};

const handleStepForward = () => {


if (currentStep < [Link] - 1) {
setCurrentStep(prev => prev + 1);
}
};

const handleStepBackward = () => {


if (currentStep > 0) {
setCurrentStep(prev => prev - 1);
}
};

const handleAlgorithmChange = (newAlgorithm: SortAlgorithm) => {


setAlgorithm(newAlgorithm);
setIsPlaying(false);
};

const handleArraySizeChange = (newSize: number) => {


setArraySize(newSize);
setIsPlaying(false);
};

return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-
slate-100">
<div className="container mx-auto px-4 py-8">
<header className="mb-8 text-center">
<div className="flex items-center justify-center gap-3 mb-2">
<Code2 size={32} className="text-blue-600" />
<h1 className="text-4xl font-bold text-gray-800">
Reorder List Code Visualizer
</h1>
</div>
<p className="text-gray-600">
Interactive sorting algorithm visualization with step-by-step
execution
</p>
</header>

<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">


<div className="lg:col-span-1">
<VisualizerControls
algorithm={algorithm}
onAlgorithmChange={handleAlgorithmChange}
arraySize={arraySize}
onArraySizeChange={handleArraySizeChange}
speed={speed}
onSpeedChange={setSpeed}
isPlaying={isPlaying}
onPlayPause={handlePlayPause}
onReset={handleReset}
onStepForward={handleStepForward}
onStepBackward={handleStepBackward}
currentStep={currentStep}
totalSteps={[Link]}
/>
</div>

<div className="lg:col-span-2 space-y-6">


{[Link] > 0 && (
<ArrayVisualizer step={steps[currentStep]} />
)}

<CodeDisplay algorithm={algorithm} />


</div>
</div>
</div>
</div>
);
}

export default App;

index: css
@tailwind base;
@tailwind components;
@tailwind utilities;

[Link]
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';

export default [Link](


{ ignores: ['dist'] },
{
extends: [[Link], ...[Link]],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: [Link],
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...[Link],
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
);

[Link]

{
"name": "vite-react-typescript-starter",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview",
"typecheck": "tsc --noEmit -p [Link]"
},
"dependencies": {
"@supabase/supabase-js": "^2.57.4",
"lucide-react": "^0.344.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@eslint/js": "^9.9.1",
"@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.18",
"eslint": "^9.9.1",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.11",
"globals": "^15.9.0",
"postcss": "^8.4.35",
"tailwindcss": "^3.4.1",
"typescript": "^5.5.3",
"typescript-eslint": "^8.3.0",
"vite": "^5.4.2"
}
}

[Link]
# Reorder List Code Visualizer

An interactive sorting algorithm visualizer built with React and TypeScript.


Watch sorting algorithms work in real-time with step-by-step execution,
color-coded visual feedback, and side-by-side code implementations.

## Features

- **5 Sorting Algorithms**: Bubble Sort, Selection Sort, Insertion Sort,


Quick Sort, and Merge Sort
- **Interactive Visualization**: Animated bars representing array elements
with real-time position updates
- **Step-by-Step Control**: Play/pause, forward/backward stepping, and
speed adjustment
- **Color-Coded Feedback**:
- Orange: Currently comparing elements
- Red: Swapping elements
- Green: Already sorted elements
- **Algorithm Complexity Display**: View time and space complexity for
each algorithm
- **Customizable Parameters**: Adjust array size (5-20 elements) and
animation speed (100-2000ms)
- **Code Display**: JavaScript implementation of each algorithm with
syntax highlighting
## Getting Started

### Prerequisites

- [Link] (v16 or higher)


- npm or yarn

### Installation

1. Clone the repository:


```bash
git clone <repository-url>
cd project
```

2. Install dependencies:
```bash
npm install
```

3. Start the development server:


```bash
npm run dev
```

The application will open in your browser at `[Link]

## Usage

1. **Select an Algorithm**: Choose from the dropdown menu in the control


panel
2. **Adjust Parameters**:
- Use the slider to change array size (5-20 elements)
- Control animation speed (100-2000ms)
3. **Control Execution**:
- Click "Play" to auto-advance through steps
- Click "Pause" to stop
- Use forward/backward buttons to step through manually
4. **Reset**: Click "Reset & Generate New" to create a new random array

## Algorithm Explanations

### Bubble Sort


- Compares adjacent elements and swaps them if they're in the wrong
order
- Repeats until the array is sorted
- **Complexity**: O(n²) time, O(1) space
- **Best for**: Educational purposes, small datasets
### Selection Sort
- Finds the minimum element in unsorted portion and moves it to its
correct position
- Repeats until entire array is sorted
- **Complexity**: O(n²) time, O(1) space
- **Best for**: When memory writes are expensive

### Insertion Sort


- Builds sorted array one item at a time by inserting each element into its
correct position
- Works similarly to sorting playing cards
- **Complexity**: O(n²) time, O(1) space
- **Best for**: Small arrays, nearly sorted data

### Quick Sort


- Divides array around a pivot and recursively sorts partitions
- Uses divide-and-conquer approach
- **Complexity**: O(n log n) average, O(1) space
- **Best for**: General-purpose sorting, most practical

### Merge Sort


- Divides array in half, recursively sorts each half, then merges them
- Guarantees O(n log n) performance
- **Complexity**: O(n log n) time, O(n) space
- **Best for**: Stable sorting, guaranteed performance

## Project Structure

```
src/
├── components/
│ ├── [Link] # Main visualization component
│ ├── [Link] # Code snippet display with complexity info
│ └── [Link] # Control panel for algorithm execution
├── utils/
│ └── [Link] # Algorithm implementations and step
generation
├── types/
│ └── [Link] # TypeScript type definitions
├── [Link] # Main application component
└── [Link] # Application entry point
```

## Technologies Used

- **React 18**: UI framework


- **TypeScript**: Type-safe JavaScript
- **Tailwind CSS**: Utility-first CSS framework
- **Lucide React**: Icon library
- **Vite**: Fast build tool and development server

## Building for Production

```bash
npm run build
```

The production build will be created in the `dist/` directory.

## Linting

```bash
npm run lint
```

## Type Checking

```bash
npm run typecheck
```

## Learning Resources

This visualizer is perfect for:


- Computer Science students learning sorting algorithms
- Developers preparing for technical interviews
- Anyone wanting to understand algorithm performance
- Teaching algorithm concepts visually

## Tips for Learning

1. **Start Simple**: Begin with Bubble Sort to understand the basic


concept
2. **Observe Patterns**: Watch how different algorithms make different
numbers of comparisons
3. **Compare Efficiency**: Switch between algorithms with the same
array to see performance differences
4. **Use Manual Stepping**: Step through algorithms manually to
understand each decision
5. **Vary Array Size**: Try different sizes to see how performance scales

## Browser Compatibility

- Chrome/Chromium (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
## Contributing

Feel free to fork this project and submit pull requests for any
improvements.

## License

This project is open source and available under the MIT License.

You might also like