- {orderedDifficulties.map((difficulty) => {
- const { count, label } = difficultyData[difficulty] || {
- count: 0,
- label: difficulty,
- };
+ {difficultyData.map((difficulty) => {
+ const label = difficulty[1].label.toLowerCase();
+ const count = difficulty[1].count;
// Get card props with fallback for unknown difficulties
- const cardProps = difficultyCardProps[difficulty] || {
+ const cardProps = difficultyCardProps[label] || {
color: "bg-gray-50 border-gray-200",
textColor: "text-gray-800",
icon: "?",
@@ -71,12 +68,14 @@ export default function DifficultiesPage() {
return (
+
{code.map((line, index) => {
// Calculate indentation to display nested blocks properly
diff --git a/components/visualizer/AlgorithmVisualizer.tsx b/components/visualizer/AlgorithmVisualizer.tsx
index 95fcb15..d48f896 100644
--- a/components/visualizer/AlgorithmVisualizer.tsx
+++ b/components/visualizer/AlgorithmVisualizer.tsx
@@ -12,7 +12,7 @@ import { SearchStep, SortingStep } from "@/lib/types";
export default function AlgorithmVisualizer() {
const { state, dispatch } = useAlgorithm();
- const { currentStep, algorithm, data, visualizationData } = state;
+ const { currentStep, algorithm, data, visualizationData, target } = state;
// Generate a new random array
const handleGenerateNewArray = () => {
@@ -25,8 +25,14 @@ export default function AlgorithmVisualizer() {
const algorithmFunction = getAlgorithmByName(algorithm);
if (algorithmFunction) {
try {
- // For search algorithms, the target will be set in the reducer
- const viz = algorithmFunction(data, state.target);
+ const newData = [...state.data];
+
+ // Special handling for binary search - ensure sorted array and target exists
+ if (algorithm === "binarySearch") {
+ newData.sort((a, b) => a - b);
+ }
+
+ const viz = algorithmFunction(newData, target);
dispatch({ type: "GENERATE_VISUALIZATION", payload: viz });
} catch (error) {
console.error("Error generating visualization:", error);
diff --git a/components/visualizer/SearchVisualization.tsx b/components/visualizer/SearchVisualization.tsx
index 47bb8c0..5fe3b2f 100644
--- a/components/visualizer/SearchVisualization.tsx
+++ b/components/visualizer/SearchVisualization.tsx
@@ -32,17 +32,14 @@ export default function SearchVisualization({
};
const updateTarget = (newTarget: number) => {
- console.log(newTarget);
// Update the target value
dispatch({ type: "SET_TARGET", payload: newTarget });
// Regenerate visualization with the new target
const algorithmFunction = getAlgorithmByName(state.algorithm);
- console.log(algorithmFunction);
if (algorithmFunction) {
try {
const viz = algorithmFunction(state.data, newTarget);
- console.log(viz);
dispatch({ type: "GENERATE_VISUALIZATION", payload: viz });
} catch (error) {
console.error("Error generating visualization:", error);
@@ -114,10 +111,15 @@ export default function SearchVisualization({
Index: {index}
{index === current && (
-
+
Current
)}
+ {value === target && (
+
+ Target
+
+ )}
);
})}
diff --git a/lib/algorithms/index.ts b/lib/algorithms/index.ts
index f64b5d0..c65bb2f 100644
--- a/lib/algorithms/index.ts
+++ b/lib/algorithms/index.ts
@@ -1,14 +1,12 @@
-import { AlgorithmVisualization, AlgorithmInfo } from "../types";
-import { bubbleSort } from "./bubbleSort";
-import { selectionSort } from "./selectionSort";
-import { insertionSort } from "./insertionSort";
-import { mergeSort } from "./mergeSort";
-import { quickSort } from "./quickSort";
-import { heapSort } from "./heapSort";
-import { linearSearch } from "./linearSearch";
-
-// Default target value for search algorithms
-const DEFAULT_TARGET = 42;
+import { AlgorithmVisualization } from "../types";
+import { bubbleSort } from "./sorting/bubbleSort";
+import { selectionSort } from "./sorting/selectionSort";
+import { insertionSort } from "./sorting/insertionSort";
+import { mergeSort } from "./sorting/mergeSort";
+import { quickSort } from "./sorting/quickSort";
+import { heapSort } from "./sorting/heapSort";
+import { linearSearch } from "./searching/linearSearch";
+import { binarySearch } from "./searching/binarySearch";
// Map algorithm names to their implementation functions
const algorithms: Record<
@@ -21,8 +19,8 @@ const algorithms: Record<
mergeSort,
quickSort,
heapSort,
- linearSearch: (array: number[]) => linearSearch(array, DEFAULT_TARGET),
- // Add more algorithms as they are implemented
+ linearSearch,
+ binarySearch,
};
// Get algorithm function by name
@@ -32,66 +30,6 @@ export function getAlgorithmByName(
return algorithms[name] || null;
}
-// List available algorithms with metadata
-export const availableAlgorithms: AlgorithmInfo[] = [
- {
- name: "Bubble Sort",
- key: "bubbleSort",
- category: "sorting",
- description:
- "A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.",
- difficulty: "easy",
- },
- {
- name: "Selection Sort",
- key: "selectionSort",
- category: "sorting",
- description:
- "The selection sort algorithm sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning.",
- difficulty: "easy",
- },
- {
- name: "Insertion Sort",
- key: "insertionSort",
- category: "sorting",
- description:
- "Insertion sort iterates through an array and at each iteration it removes one element, finds the location where it belongs and inserts it there.",
- difficulty: "easy",
- },
- {
- name: "Merge Sort",
- key: "mergeSort",
- category: "sorting",
- description:
- "Merge sort is a divide and conquer algorithm that divides the input array into two halves, recursively sorts them, and then merges the sorted halves.",
- difficulty: "medium",
- },
- {
- name: "Quick Sort",
- key: "quickSort",
- category: "sorting",
- description:
- "Quick sort is a divide and conquer algorithm that picks an element as a pivot and partitions the array around the pivot.",
- difficulty: "medium",
- },
- {
- name: "Heap Sort",
- key: "heapSort",
- category: "sorting",
- description:
- "Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure to build a max-heap and then extract elements in order.",
- difficulty: "hard",
- },
- {
- name: "Linear Search",
- key: "linearSearch",
- category: "searching",
- description:
- "Linear search sequentially checks each element of the list until it finds an element that matches the target value.",
- difficulty: "easy",
- },
-];
-
// Export all algorithms
export {
bubbleSort,
@@ -101,4 +39,5 @@ export {
quickSort,
heapSort,
linearSearch,
+ binarySearch,
};
diff --git a/lib/algorithms/metadata.ts b/lib/algorithms/metadata.ts
new file mode 100644
index 0000000..15e1c26
--- /dev/null
+++ b/lib/algorithms/metadata.ts
@@ -0,0 +1,76 @@
+import { AlgorithmInfo } from "../types";
+
+export const availableAlgorithms: Record
= {
+ bubbleSort: {
+ name: "Bubble Sort",
+ key: "bubbleSort",
+ category: "sorting",
+ subtitle: "Simple but inefficient comparison sort",
+ description:
+ "A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. With a time complexity of O(n²), it's inefficient for large datasets but is easy to implement and understand. The algorithm gets its name because smaller elements 'bubble' to the top of the list with each iteration.",
+ difficulty: "easy",
+ },
+ selectionSort: {
+ name: "Selection Sort",
+ key: "selectionSort",
+ category: "sorting",
+ subtitle: "In-place comparison sort with O(n²) complexity",
+ description:
+ "The selection sort algorithm sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning. Unlike bubble sort, it makes only O(n) swaps, making it useful when write/swap operations are expensive. However, its O(n²) time complexity makes it inefficient for large datasets. Selection sort is not stable, meaning equal elements might not maintain their relative positions.",
+ difficulty: "easy",
+ },
+ insertionSort: {
+ name: "Insertion Sort",
+ key: "insertionSort",
+ category: "sorting",
+ subtitle: "Efficient for small data sets and nearly sorted arrays",
+ description:
+ "Insertion sort iterates through an array and at each iteration it removes one element, finds the location where it belongs and inserts it there. While it has an average time complexity of O(n²), it performs exceptionally well on small or nearly-sorted arrays with best-case O(n) performance. Insertion sort is an adaptive, stable, in-place algorithm that works similarly to how people sort playing cards in their hands.",
+ difficulty: "easy",
+ },
+ mergeSort: {
+ name: "Merge Sort",
+ key: "mergeSort",
+ category: "sorting",
+ subtitle: "Stable, divide-and-conquer algorithm with O(n log n) complexity",
+ description:
+ "Merge sort is a divide and conquer algorithm that divides the input array into two halves, recursively sorts them, and then merges the sorted halves. With a consistent O(n log n) time complexity regardless of input data, it outperforms simpler algorithms on large datasets. While requiring O(n) auxiliary space for the merging process, it guarantees stability and is particularly efficient for linked lists. Merge sort is often used in external sorting when data doesn't fit in memory.",
+ difficulty: "medium",
+ },
+ quickSort: {
+ name: "Quick Sort",
+ key: "quickSort",
+ category: "sorting",
+ subtitle: "Fast, in-place sorting with average O(n log n) performance",
+ description:
+ "Quick sort is a divide and conquer algorithm that picks an element as a pivot and partitions the array around the pivot. With an average time complexity of O(n log n) and minimal space requirements, it's typically faster in practice than other O(n log n) algorithms like merge sort. However, it has a worst-case time complexity of O(n²) with poor pivot selection and is not stable. Quick sort is widely used and serves as the foundation for many programming language sorting implementations.",
+ difficulty: "medium",
+ },
+ heapSort: {
+ name: "Heap Sort",
+ key: "heapSort",
+ category: "sorting",
+ subtitle: "Comparison-based sort using binary heap structure",
+ description:
+ "Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure to build a max-heap and then repeatedly extracts the maximum element. With a guaranteed O(n log n) time complexity regardless of input data and O(1) auxiliary space, it combines many advantages of insertion sort and merge sort. While not stable and slightly slower than quick sort in practice, heap sort provides reliable performance without the risk of worst-case scenarios, making it valuable for systems requiring consistent performance.",
+ difficulty: "hard",
+ },
+ linearSearch: {
+ name: "Linear Search",
+ key: "linearSearch",
+ category: "searching",
+ subtitle: "Simple O(n) search through unsorted collections",
+ description:
+ "Linear search sequentially checks each element of the list until it finds an element that matches the target value. With a time complexity of O(n), it's the simplest searching algorithm but becomes inefficient for large datasets. One advantage is that it works on unsorted arrays and doesn't require any preprocessing. Linear search is practical for small arrays or when the target is likely to be found early in the sequence. It's also useful when searching rarely happens or when elements are frequently added and removed.",
+ difficulty: "easy",
+ },
+ binarySearch: {
+ name: "Binary Search",
+ key: "binarySearch",
+ category: "searching",
+ subtitle: "Efficient O(log n) search for sorted collections",
+ description:
+ "Binary search finds the position of a target value within a sorted array by repeatedly dividing the search interval in half. With a logarithmic time complexity of O(log n), it's dramatically more efficient than linear search for large datasets. Binary search requires the array to be sorted beforehand, making it ideal for situations where searching occurs frequently on relatively static data. This algorithm is the foundation for many efficient data structures like binary search trees and is widely used in database systems, dictionaries, and numerous programming applications.",
+ difficulty: "medium",
+ },
+};
diff --git a/lib/algorithms/searching/binarySearch.ts b/lib/algorithms/searching/binarySearch.ts
new file mode 100644
index 0000000..0f74072
--- /dev/null
+++ b/lib/algorithms/searching/binarySearch.ts
@@ -0,0 +1,95 @@
+import { AlgorithmVisualization, SearchStep } from "../../types";
+import { createVisualization } from "../utils";
+
+export function binarySearch(
+ array: number[],
+ target: number = 42
+): AlgorithmVisualization {
+ const steps: SearchStep[] = [];
+ // Make a copy of the array and sort it (binary search requires a sorted array)
+ const arr = [...array].sort((a, b) => a - b);
+ const visited: number[] = [];
+
+ // Initial state
+ steps.push({
+ array: [...arr],
+ current: -1,
+ target: target,
+ found: false,
+ visited: [],
+ });
+
+ let left = 0;
+ let right = arr.length - 1;
+ let found = false;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+
+ // Add current index to visited
+ visited.push(mid);
+
+ // Record the step of examining the middle value
+ steps.push({
+ array: [...arr],
+ current: mid,
+ target: target,
+ found: false,
+ visited: [...visited],
+ });
+
+ // Check if middle element is the target
+ if (arr[mid] === target) {
+ // Found the target
+ steps.push({
+ array: [...arr],
+ current: mid,
+ target: target,
+ found: true,
+ visited: [...visited],
+ });
+ found = true;
+ break;
+ } else if (arr[mid] < target) {
+ // Target is in the right half
+ left = mid + 1;
+ } else {
+ // Target is in the left half
+ right = mid - 1;
+ }
+ }
+
+ // If target was not found
+ if (!found) {
+ steps.push({
+ array: [...arr],
+ current: -1,
+ target: target,
+ found: false,
+ visited: [...visited],
+ });
+ }
+
+ return createVisualization("binarySearch", steps, {
+ timeComplexity: "O(log n)",
+ spaceComplexity: "O(1)",
+ reference: "https://en.wikipedia.org/wiki/Binary_search_algorithm",
+ pseudoCode: [
+ "procedure binarySearch(arr: sorted array, target: element)",
+ " left := 0",
+ " right := length(arr) - 1",
+ " while left <= right do",
+ " mid := floor((left + right) / 2)",
+ " if arr[mid] = target then",
+ " return mid // Target found at index mid",
+ " else if arr[mid] < target then",
+ " left := mid + 1 // Target is in the right half",
+ " else",
+ " right := mid - 1 // Target is in the left half",
+ " end if",
+ " end while",
+ " return -1 // Target not found",
+ "end procedure",
+ ],
+ });
+}
diff --git a/lib/algorithms/linearSearch.ts b/lib/algorithms/searching/linearSearch.ts
similarity index 68%
rename from lib/algorithms/linearSearch.ts
rename to lib/algorithms/searching/linearSearch.ts
index acf022e..124c41f 100644
--- a/lib/algorithms/linearSearch.ts
+++ b/lib/algorithms/searching/linearSearch.ts
@@ -1,5 +1,5 @@
-// lib/algorithms/linearSearch.ts
-import { AlgorithmVisualization, SearchStep } from "../types";
+import { AlgorithmVisualization, SearchStep } from "../../types";
+import { createVisualization } from "../utils";
export function linearSearch(
array: number[],
@@ -9,14 +9,11 @@ export function linearSearch(
const arr = [...array];
const visited: number[] = [];
- // Set a default target if one is not provided or not found in the array
- const targetValue = target || 42;
-
// Initial state
steps.push({
array: [...arr],
current: -1,
- target: targetValue,
+ target: target,
found: false,
visited: [],
});
@@ -30,18 +27,18 @@ export function linearSearch(
steps.push({
array: [...arr],
current: i,
- target: targetValue,
+ target: target,
found: false,
visited: [...visited],
});
// Check if current element equals target
- if (arr[i] === targetValue) {
+ if (arr[i] === target) {
// Found the target, record final step
steps.push({
array: [...arr],
current: i,
- target: targetValue,
+ target: target,
found: true,
visited: [...visited],
});
@@ -54,19 +51,13 @@ export function linearSearch(
steps.push({
array: [...arr],
current: -1,
- target: targetValue,
+ target: target,
found: false,
visited: [...visited],
});
}
- return {
- steps,
- name: "Linear Search",
- key: "linearSearch",
- category: "searching",
- description:
- "Linear search is a simple search algorithm that finds the position of a target value within a list by checking each element sequentially until a match is found or the end of the list is reached.",
+ return createVisualization("linearSearch", steps, {
timeComplexity: "O(n)",
spaceComplexity: "O(1)",
reference: "https://en.wikipedia.org/wiki/Linear_search",
@@ -80,5 +71,5 @@ export function linearSearch(
" return -1 // Target not found",
"end procedure",
],
- };
+ });
}
diff --git a/lib/algorithms/bubbleSort.ts b/lib/algorithms/sorting/bubbleSort.ts
similarity index 84%
rename from lib/algorithms/bubbleSort.ts
rename to lib/algorithms/sorting/bubbleSort.ts
index 83af5be..1eadc5e 100644
--- a/lib/algorithms/bubbleSort.ts
+++ b/lib/algorithms/sorting/bubbleSort.ts
@@ -1,4 +1,5 @@
-import { AlgorithmVisualization, SortingStep } from "../types";
+import { AlgorithmVisualization, SortingStep } from "../../types";
+import { createVisualization } from "../utils";
export function bubbleSort(array: number[]): AlgorithmVisualization {
const steps: SortingStep[] = [];
@@ -55,13 +56,7 @@ export function bubbleSort(array: number[]): AlgorithmVisualization {
if (!swapped) break;
}
- return {
- steps,
- name: "Bubble Sort",
- key: "bubbleSort",
- category: "sorting",
- description:
- "A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.",
+ return createVisualization("bubbleSort", steps, {
timeComplexity: "O(n²)",
spaceComplexity: "O(1)",
reference: "https://en.wikipedia.org/wiki/Bubble_sort",
@@ -80,5 +75,5 @@ export function bubbleSort(array: number[]): AlgorithmVisualization {
" until not swapped",
"end procedure",
],
- };
+ });
}
diff --git a/lib/algorithms/heapSort.ts b/lib/algorithms/sorting/heapSort.ts
similarity index 91%
rename from lib/algorithms/heapSort.ts
rename to lib/algorithms/sorting/heapSort.ts
index c1c973c..146e637 100644
--- a/lib/algorithms/heapSort.ts
+++ b/lib/algorithms/sorting/heapSort.ts
@@ -1,4 +1,5 @@
-import { AlgorithmVisualization, SortingStep } from "../types";
+import { AlgorithmVisualization, SortingStep } from "../../types";
+import { createVisualization } from "../utils";
export function heapSort(array: number[]): AlgorithmVisualization {
const steps: SortingStep[] = [];
@@ -56,13 +57,7 @@ export function heapSort(array: number[]): AlgorithmVisualization {
completed: [...completed],
});
- return {
- steps,
- name: "Heap Sort",
- key: "heapSort",
- category: "sorting",
- description:
- "A comparison-based sorting algorithm that uses a binary heap data structure. It divides the input into a sorted and an unsorted region, and iteratively shrinks the unsorted region by extracting the largest element and moving it to the sorted region.",
+ return createVisualization("heapSort", steps, {
timeComplexity: "O(n log n)",
spaceComplexity: "O(1)",
reference: "https://en.wikipedia.org/wiki/Heapsort",
@@ -99,7 +94,7 @@ export function heapSort(array: number[]): AlgorithmVisualization {
" end if",
"end procedure",
],
- };
+ });
}
function buildMaxHeap(
diff --git a/lib/algorithms/insertionSort.ts b/lib/algorithms/sorting/insertionSort.ts
similarity index 85%
rename from lib/algorithms/insertionSort.ts
rename to lib/algorithms/sorting/insertionSort.ts
index 3852edb..5cfcb50 100644
--- a/lib/algorithms/insertionSort.ts
+++ b/lib/algorithms/sorting/insertionSort.ts
@@ -1,4 +1,5 @@
-import { AlgorithmVisualization, SortingStep } from "../types";
+import { AlgorithmVisualization, SortingStep } from "../../types";
+import { createVisualization } from "../utils";
export function insertionSort(array: number[]): AlgorithmVisualization {
const steps: SortingStep[] = [];
@@ -64,13 +65,7 @@ export function insertionSort(array: number[]): AlgorithmVisualization {
});
}
- return {
- steps,
- name: "Insertion Sort",
- key: "insertionSort",
- category: "sorting",
- description:
- "Insertion sort iterates through an array and at each iteration it removes one element, finds the location where it belongs and inserts it there.",
+ return createVisualization("insertionSort", steps, {
timeComplexity: "O(n²)",
spaceComplexity: "O(1)",
reference: "https://en.wikipedia.org/wiki/Insertion_sort",
@@ -88,5 +83,5 @@ export function insertionSort(array: number[]): AlgorithmVisualization {
" end for",
"end procedure",
],
- };
+ });
}
diff --git a/lib/algorithms/mergeSort.ts b/lib/algorithms/sorting/mergeSort.ts
similarity index 93%
rename from lib/algorithms/mergeSort.ts
rename to lib/algorithms/sorting/mergeSort.ts
index e4986cf..3d73b2d 100644
--- a/lib/algorithms/mergeSort.ts
+++ b/lib/algorithms/sorting/mergeSort.ts
@@ -1,4 +1,5 @@
-import { AlgorithmVisualization, SortingStep } from "../types";
+import { AlgorithmVisualization, SortingStep } from "../../types";
+import { createVisualization } from "../utils";
export function mergeSort(array: number[]): AlgorithmVisualization {
const steps: SortingStep[] = [];
@@ -29,13 +30,7 @@ export function mergeSort(array: number[]): AlgorithmVisualization {
completed: finalCompleted,
});
- return {
- steps,
- name: "Merge Sort",
- key: "mergeSort",
- category: "sorting",
- description:
- "A divide and conquer algorithm that divides the input array in two halves, recursively sorts them, and then merges the sorted halves.",
+ return createVisualization("mergeSort", steps, {
timeComplexity: "O(n log n)",
spaceComplexity: "O(n)",
reference: "https://en.wikipedia.org/wiki/Merge_sort",
@@ -75,7 +70,7 @@ export function mergeSort(array: number[]): AlgorithmVisualization {
" end for",
"end procedure",
],
- };
+ });
}
function mergeSortHelper(
diff --git a/lib/algorithms/quickSort.ts b/lib/algorithms/sorting/quickSort.ts
similarity index 92%
rename from lib/algorithms/quickSort.ts
rename to lib/algorithms/sorting/quickSort.ts
index be4d390..bf7b79b 100644
--- a/lib/algorithms/quickSort.ts
+++ b/lib/algorithms/sorting/quickSort.ts
@@ -1,4 +1,5 @@
-import { AlgorithmVisualization, SortingStep } from "../types";
+import { AlgorithmVisualization, SortingStep } from "../../types";
+import { createVisualization } from "../utils";
export function quickSort(array: number[]): AlgorithmVisualization {
const steps: SortingStep[] = [];
@@ -26,13 +27,7 @@ export function quickSort(array: number[]): AlgorithmVisualization {
completed: finalCompleted,
});
- return {
- steps,
- name: "Quick Sort",
- key: "quickSort",
- category: "sorting",
- description:
- "A divide and conquer algorithm that picks an element as a pivot and partitions the array around the chosen pivot.",
+ return createVisualization("quickSort", steps, {
timeComplexity: "O(n log n) - average, O(n²) - worst case",
spaceComplexity: "O(log n)",
reference: "https://en.wikipedia.org/wiki/Quicksort",
@@ -58,7 +53,7 @@ export function quickSort(array: number[]): AlgorithmVisualization {
" return i + 1",
"end procedure",
],
- };
+ });
}
function quickSortHelper(
diff --git a/lib/algorithms/selectionSort.ts b/lib/algorithms/sorting/selectionSort.ts
similarity index 86%
rename from lib/algorithms/selectionSort.ts
rename to lib/algorithms/sorting/selectionSort.ts
index 99fcb6c..9646988 100644
--- a/lib/algorithms/selectionSort.ts
+++ b/lib/algorithms/sorting/selectionSort.ts
@@ -1,4 +1,5 @@
-import { AlgorithmVisualization, SortingStep } from "../types";
+import { AlgorithmVisualization, SortingStep } from "../../types";
+import { createVisualization } from "../utils";
export function selectionSort(array: number[]): AlgorithmVisualization {
const steps: SortingStep[] = [];
@@ -74,13 +75,7 @@ export function selectionSort(array: number[]): AlgorithmVisualization {
completed: [...completed],
});
- return {
- steps,
- name: "Selection Sort",
- key: "selectionSort",
- category: "sorting",
- description:
- "The selection sort algorithm sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning.",
+ return createVisualization("selectionSort", steps, {
timeComplexity: "O(n²)",
spaceComplexity: "O(1)",
reference: "https://en.wikipedia.org/wiki/Selection_sort",
@@ -100,5 +95,5 @@ export function selectionSort(array: number[]): AlgorithmVisualization {
" end for",
"end procedure",
],
- };
+ });
}
diff --git a/lib/algorithms/utils.ts b/lib/algorithms/utils.ts
new file mode 100644
index 0000000..19fc359
--- /dev/null
+++ b/lib/algorithms/utils.ts
@@ -0,0 +1,33 @@
+import { AlgorithmVisualization, SearchStep, SortingStep } from "../types";
+import { availableAlgorithms } from "./metadata";
+
+/**
+ * Helper function to create an AlgorithmVisualization object from steps and algorithm-specific details
+ * This eliminates duplication between the metadata and the algorithm implementation
+ */
+export function createVisualization(
+ key: keyof typeof availableAlgorithms,
+ steps: SortingStep[] | SearchStep[],
+ details: {
+ timeComplexity: string;
+ spaceComplexity: string;
+ reference: string;
+ pseudoCode: string[];
+ }
+): AlgorithmVisualization {
+ const metadata = availableAlgorithms[key];
+
+ if (!metadata) {
+ throw new Error(`Metadata for algorithm "${String(key)}" not found`);
+ }
+
+ return {
+ steps,
+ name: metadata.name,
+ key: metadata.key,
+ category: metadata.category,
+ difficulty: metadata.difficulty,
+ description: metadata.description,
+ ...details,
+ };
+}
diff --git a/lib/types.ts b/lib/types.ts
index ab59780..e92568c 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -22,6 +22,7 @@ export interface AlgorithmVisualization {
reference: string;
pseudoCode: string[];
category: string;
+ difficulty: string;
key: string;
}
@@ -35,6 +36,7 @@ export interface AlgorithmInfo {
name: string;
key: string;
category: AlgorithmCategory;
+ subtitle: string;
description: string;
difficulty: "easy" | "medium" | "hard";
}
diff --git a/lib/utils.ts b/lib/utils.ts
index 791ad20..fbfd39b 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -9,51 +9,8 @@ export function generateRandomArray(
);
}
-export function getAlgorithmLabel(algorithmKey: string): string {
- const labels: Record = {
- bubbleSort: "Bubble Sort",
- selectionSort: "Selection Sort",
- insertionSort: "Insertion Sort",
- mergeSort: "Merge Sort",
- quickSort: "Quick Sort",
- heapSort: "Heap Sort",
- linearSearch: "Linear Search",
- };
-
- return labels[algorithmKey] || algorithmKey;
-}
-
-export function getDifficulty(algorithmKey: string): string {
- const difficulties: Record = {
- bubbleSort: "Easy",
- selectionSort: "Easy",
- insertionSort: "Easy",
- mergeSort: "Medium",
- quickSort: "Medium",
- heapSort: "Hard",
- linearSearch: "Easy",
- };
-
- return difficulties[algorithmKey] || "Unknown";
-}
-
export function getRandomValueFromArray(array: number[]): number {
if (array.length === 0) return 42;
const randomIndex = Math.floor(Math.random() * array.length);
return array[randomIndex];
}
-
-// Ensure the target value exists in the array for demo purposes
-export function ensureTargetInArray(array: number[], target: number): number[] {
- if (array.length === 0) return [target];
-
- // If target is not in the array, replace a random element with it
- if (!array.includes(target)) {
- const newArray = [...array];
- const randomIndex = Math.floor(Math.random() * newArray.length);
- newArray[randomIndex] = target;
- return newArray;
- }
-
- return array;
-}