Skip to content

Latest commit

 

History

History
685 lines (524 loc) · 26.5 KB

AlgorithmDocumentation.md

File metadata and controls

685 lines (524 loc) · 26.5 KB

###############################################################################

Algorithm Documentation

###############################################################################

Reference for every algorithm implemented in AlgorithmVisualizer.

Covers purpose, how it works step by step, complexity, properties, and

what the visualization highlights.

###############################################################################


Table of Contents.

  1. Sorting Algorithms

  2. Searching Algorithms

  3. Pathfinding Algorithms

  4. Data Structures


Sorting Algorithms.

All sorting algorithms operate on integer array and produce a sequence of snapshots that the frontend replays. Each snapshot records: the current array state, indices being compared, indices being swapped, indices already sorted, and the pivot index (if applicable).


Bubble Sort.

What it does: Repeatedly scans the array and swaps adjacent elements that are out of order. After each full pass, the largest unsorted element "bubbles" to its correct position at the end.

How it works: 1. For each pass 'i' from '0' to 'n-1': - Compare adjacent pairs 'arr[j]' and 'arr[j+a]' for 'j' from '0' to 'n-i-2' - If 'arr[j] > arr[j+1]', swap them - After the pass, 'arr[n-i-1]' is in its final sorted position 2. If a full pass completes with zero swaps, the array is already sorted (exit early).

Properties:

Property Value
Best Case O(n) - already sorted, early exit
Average Case O(n²)
Worst Case O(n²)
Space O(1) - in-place
Stable Yes
------------------------ ---------------------------------------

Visualization Highlights:

  • Yellow Bars: the two elements currently being compared.
  • Red Bars: elements being swapped.
  • Green Bars: elements confirmed in their final sorted position.

Selection Sort.

What it does: On each pass, finds the minimum element in the unsorted portion and moves it to the front.

How it works: 1. For each position 'i' from '0' to 'n-2': - Scan positions 'i+1' through 'n-1' to find the index 'min_idx' of the smallest element. - Swap 'arr[i]' with 'arr[min_idx]' - 'arr[i]' is now in its final sorted position

Properties:

Property Value
Best Case O(n²)
Average Case O(n²)
Worst Case O(n²)
Space O(1) - in-place
Stable No (long-range swaps can reorder)
------------------------ ---------------------------------------

Note: Selection Sort always makes exactly 'n-1' swaps regardless of input order, making it useful when write operations are expensive.

Visualization Highlights:

  • Yellow Bars: the current position 'i' and the candidate minimum being compared.
  • Red Bars: the swap placing the minimum into its final position.
  • Green Bars: elements confirmed sorted.

Insertion Sort

What it does: Builds a sorted subarray from left to right. Each new element is inserted into its correct position within the already-sorted prefix.

How it works: 1. Start with a sorted subarray of size 1 (the fist element). 2. For each element 'arr[i]' (from 'i=1' to 'n-1'): - Store the element as 'key' - Shift elements in the sorted subarray that are greater than 'key' one position to the right - Insert 'key' into the gap that opens up

Properties:

Property Value
Best Case O(n) - already sorted
Average Case O(n²)
Worst Case O(n²) - reverse sorted
Space O(1) - in-place
Stable Yes
------------------------ ---------------------------------------

Note: Insertion Sort is very efficient for small arrays and nearly-sorted data. It is the algorithm of choice for small subarrays in hybrid sorts (like Timsort).

Visualization Highlights:

  • Yellow Bars: the key element and the position being compared against it.
  • Red Bars: elements being shifted right.
  • Green Bars: the sorted portion of the array.

Merge Sort

What it does: Divides the array in half recursively until subarrays have one element, then merges them back in sorted order.

How it works: 1. Divide: Split the array at the midpoint into left and right halves. 2. Recursively sort each half. 3. Merge: Walk pointers through both sorted halves simultaneously; always pick the smaller element and place it into the output array. 4. Copy the merged result back to the original array segment.

Properties:

Property Value
Best Case O(n log n)
Average Case O(n log n)
Worst Case O(n log n)
Space O(n) - requires auxiliary array
Stable Yes
------------------------ ---------------------------------------

Note: Merge Sort guarantees O(n log n) in all cases, unlyke Quick Sort. Its auxiliary space requirement is the trade-off-.

Visualization Highlights:

  • Yellow Bars: elements currently being compared during a merge step.
  • Red Bars: elements being placed back into the main array.
  • Green Bars: fully merged and sorted segments.

Quick Sort

What it does: Selects a pivot element and partitions the array so every element smaller than the pivot is to its left and every larger element is to its right. Recursively sorts each partition.

How it works (Lomuto partition scheme): 1. Choose the last element as the pivot 2. Initialize 'i = low - 1' 3. For each element from 'low' to 'high-1': if it is ≤ pivot, increment 'i' and swap 'arr[i]' with 'arr[j]' 4. Swap the pivot into position 'i+a'. The pivot is now in its final sorted position 5. Recursively apply to left partition '[low, pivot-1]' and right partition '[pivot+1, high]'

Properties:

Property Value
Best Case O(n log n)
Average Case O(n log n)
Worst Case O(n²) - when pivot is min or max
Space O(log n) - recursive call stack
Stable No
------------------------ ---------------------------------------

Note: Despite the O(n²) worst case, Quick Sort is often the fastest in practice due to cache efficiency and low constant factors.

Visualization Highlights:

  • Purple Bars: the current pivot element.
  • Yellow Bars: elements being compared against the pivot.
  • Red Bars: elements being swapped during partitioning.
  • Green Bars: elements in their final sorted position.

Heap Sort

What it does: Builds a max-heap from the array, then repeatedly extracts the maximum element (root) and places it at the end of the array.

How it works: 1. Build max-heap: Starting from the last non-leaf node '(n//2 - 1)' down to '0', call 'heapify' on each node 2. Extract phase: For 'i' from 'n-1' down to '1': - Swap 'arr[0]' (max) with 'arr[i]' - 'arr[i]' is now in its final sorted position - Call 'heapify' on the reduced heap '[0, i-1]' 3. Heapify: Given a node 'i', ensure it is larger than its children. If not, swap with the larger child and repeat downward.

Properties:

Property Value
Best Case O(n log n)
Average Case O(n log n)
Worst Case O(n log n)
Space O(1) - in-place
Stable No
------------------------ ---------------------------------------

Note: Heap Sort has the same asymptotic complexitu as Merge Sort but requires no extra space like Quick Sort, while guaranteeing O(n log n) unlike Quick Sort.

Visualization Highlights:

  • Yellow Bars: nodes being compared during heapify.
  • Red Bars: elements being swapped to maintain the heap property.
  • Green Bars: elements extracted and placed in their final sorted position.

Shell Sort

What it does: What it does: A generalization of Insertion Sort that allows the exchange of elements that are far apart. It progressively reduces the gap between compared elements until the gap is 1 (a final Insertion Sort pass on a nearly-sorted array).

How it works:

  1. Start with a gap gap = n // 2.
  2. Perform a gapped Insertion Sort: compare and shift elements that are gap positions apart.
  3. Reduce gap by half (gap //= 2) and repeat.
  4. When gap = 1, the algorithm performs a standard Insertion Sort, which is fast because the array is nearly sorted.

Properties:

Property Value
Best case O(n log n)
Average case O(n log² n)
Worst case O(n²) (depends on gap sequence)
Space O(1) — in-place
Stable No

Note: Performance depends heavily on the gap sequence used. The n//2 halving sequence is simple but not optimal; Knuth's sequence (3^k - 1) / 2 performs better in practice.

Visualization highlights:

  • Yellow bars: the two elements being compared across the current gap.
  • Red bars: elements being shifted or swapped.
  • Green bars: fully sorted elements.

Searching Algorithms

Searching algorithms operate on integer arrays and find whether a target value exists and at which index.


Linear Search

What it does: Scans every element in the array from left to right until the target is found or the entire array has been checked.

How it works:

  1. For each index i from 0 to n-1:
    • Compare arr[i] with the target.
    • If equal, return i (target found).
  2. If the loop completes without a match, return -1 (not found).

Properties:

Property Value
Best case O(1) — target is first element
Average case O(n)
Worst case O(n)
Space O(1)
Requires sorted input No

When to use: When the array is unsorted, very small, or when searching only once (not worth the O(n log n) sort needed for Binary Search).

Visualization highlights:

  • Yellow bar: the element currently being examined.
  • Green bar: the element when found.

Binary Search

What it does: Exploits the sorted order of an array to eliminate half of the remaining candidates on each step, homing in on the target exponentially faster than Linear Search.

How it works:

  1. Sort the input array (required for correctness).
  2. Maintain low = 0 and high = n - 1.
  3. While low <= high:
    • Compute mid = (low + high) // 2.
    • If arr[mid] == target, return mid.
    • If arr[mid] < target, set low = mid + 1 (search right half).
    • If arr[mid] > target, set high = mid - 1 (search left half).
  4. If the loop ends, return -1 (not found).

Properties:

Property Value
Best case O(1) — target is the midpoint
Average case O(log n)
Worst case O(log n)
Space O(1)
Requires sorted input Yes

When to use: When the data is sorted and searches are repeated. Sorting once (O(n log n)) amortizes across many O(log n) searches.

Visualization highlights:

  • Purple range: the current active search window [low, high].
  • Red bar: the mid element being compared this step.
  • Gray bars: elements outside the search range (excluded).
  • Green bar: the element when found.

Pathfinding Algorithms

All pathfinding algorithms operate on a 2D grid (20 rows × 40 columns). Cells are either passable (0) or walls (1). Movement is 4-directional (up, down, left, right — no diagonals). All edges have unit cost (weight = 1).

Each snapshot records: visited cells, frontier cells, current cell, found flag, and the final path.


BFS (Breadth-First Search)

What it does: Explores cells level by level (all cells 1 step away, then 2 steps, then 3…). Because it explores in order of distance, it always finds the shortest path in an unweighted grid.

How it works:

  1. Initialize a queue with the start cell. Mark it as visited.
  2. While the queue is not empty:
    • Dequeue the front cell (r, c).
    • If it is the goal, reconstruct the path and stop.
    • For each of the 4 neighbors: if in bounds, not a wall, and not yet visited:
      • Mark as visited.
      • Record parent (for path reconstruction).
      • Enqueue.
  3. If the queue empties without reaching the goal, no path exists.
  4. Path reconstruction: Walk backwards from goal to start via parent pointers, then reverse.

Properties:

Property Value
Time O(V + E) where V = cells, E = edges
Space O(V)
Finds shortest path Yes (unweighted)
Complete Yes

Visualization highlights:

  • Orange cells: frontier (cells in the queue, to be explored).
  • Purple cells: visited (already dequeued and processed).
  • Yellow cells: the final shortest path.

DFS (Depth-First Search)

What it does: Explores as far as possible along one branch before backtracking to try another. It is not guaranteed to find the shortest path.

How it works (recursive):

  1. Mark the current cell as visited.
  2. If it is the goal, set the found flag and return.
  3. For each of the 4 neighbors (up, down, left, right):
    • If in bounds, not a wall, and not visited:
      • Record parent.
      • Push onto the conceptual stack (visualization).
      • Recurse.
      • If found during recursion, return immediately (no more branches needed).
  4. If no neighbor leads to the goal, backtrack (pop from stack in visualization).

Properties:

Property Value
Time O(V + E)
Space O(V) — recursion depth
Finds shortest path No
Complete Yes (on finite grids)

When to use: When any path (not necessarily shortest) suffices, or for maze generation. DFS is often used to explore the structure of graphs rather than to find optimal routes.

Visualization highlights:

  • Orange cells: the implicit DFS stack (cells pushed but not yet backtracked from).
  • Purple cells: visited cells.
  • Yellow cells: the path DFS found (not necessarily shortest).

Dijkstra's Algorithm

What it does: Finds the shortest path in a weighted graph by always expanding the node with the smallest known cumulative distance from the start. On a unit-weight grid it behaves identically to BFS but is designed for general edge weights.

How it works:

  1. Initialize a min-heap with (distance=0, start). Set dist[start] = 0, all others ∞.
  2. While the heap is not empty:
    • Pop the node (d, r, c) with minimum distance.
    • If already visited (a better path was found earlier), skip.
    • Mark as visited.
    • If it is the goal, reconstruct path and stop.
    • For each neighbor: compute new_dist = d + edge_weight.
      • If new_dist < dist[neighbor], update dist[neighbor], record parent, push (new_dist, neighbor) to heap.
  3. Path reconstruction via parent pointers.

Properties:

Property Value
Time O((V + E) log V)
Space O(V)
Finds shortest path Yes (non-negative weights)
Weighted Yes

Note: On this unit-weight grid, Dijkstra and BFS produce identical paths. Dijkstra's generality makes it applicable to real weighted maps, routing networks, etc.

Visualization highlights:

  • Orange cells: frontier nodes in the priority queue.
  • Purple cells: settled (visited) nodes.
  • Yellow cells: the optimal shortest path.

A* (A-Star)

What it does: An informed search that combines Dijkstra's shortest-path guarantee with a heuristic that estimates remaining distance to the goal. This allows it to explore far fewer cells than Dijkstra while still finding the optimal path.

How it works:

  1. For each node, compute f = g + h:
    • g: actual cost from start to this node.
    • h: heuristic estimate of cost from this node to goal (Manhattan distance: |r - goal_r| + |c - goal_c|).
  2. Initialize a min-heap with (f=h(start), start). Set g[start] = 0.
  3. While the heap is not empty:
    • Pop the node with minimum f.
    • If already visited, skip.
    • Mark as visited.
    • If it is the goal, reconstruct path and stop.
    • For each neighbor: compute new_g = g[current] + 1.
      • If new_g < g[neighbor], update g[neighbor], compute new f, record parent, push to heap.

Properties:

Property Value
Time O((V + E) log V)
Space O(V)
Finds shortest path Yes (with admissible heuristic)
Weighted Yes

Why Manhattan distance is admissible: It never overestimates the actual cost because diagonal moves are not allowed, so the true path cost is always ≥ |Δr| + |Δc|.

Visualization highlights:

  • Orange cells: open set (nodes to be explored, sorted by f).
  • Purple cells: closed set (settled nodes).
  • Yellow cells: the optimal shortest path found.

Data Structures


Binary Search Tree (BST)

What it does: A tree where each node has at most two children, with the invariant that all values in the left subtree are less than the node's value, and all values in the right subtree are greater.

Operations:

Insert:

  1. Start at the root.
  2. If the value is less than current node, go left; if greater, go right.
  3. When a null position is reached, create a new node there.

Search:

  1. Start at the root.
  2. Compare target with current node: if equal, found. If less, go left. If greater, go right.
  3. If null is reached, target does not exist.

Delete:

  • No children: Remove the node directly.
  • One child: Replace the node with its only child.
  • Two children: Find the in-order successor (smallest node in right subtree), copy its value into the current node, then delete the successor from the right subtree.

In-order traversal:

  • Recursively visit: left subtree → current node → right subtree.
  • Produces values in ascending sorted order.

Properties:

Property Value
Search O(h) where h = tree height
Insert O(h)
Delete O(h)
Best/Average h O(log n) — balanced tree
Worst h O(n) — degenerate (sorted input)

Visualization highlights:

  • Blue nodes: default state.
  • Yellow node: currently active node (the one being inserted, searched, or compared against).
  • Green node: target found.
  • Red node: node marked for deletion.

Min/Max Heap

What it does: A complete binary tree stored as an array where each parent is smaller (min-heap) or larger (max-heap) than its children. Enables O(log n) insertion and extraction of the minimum/maximum.

Array representation:

  • Parent of node i: (i - 1) // 2
  • Left child of node i: 2*i + 1
  • Right child of node i: 2*i + 2

Operations:

Insert:

  1. Append the new element to the end of the array.
  2. Sift up: Compare with parent. If it violates heap property (smaller than parent for min-heap), swap and continue upward until the property is restored.

Extract min/max:

  1. The root holds the min/max.
  2. Replace root with the last element in the array and remove the last element.
  3. Sift down: Compare root with its children. Swap with the smaller child (min-heap) or larger child (max-heap) if the heap property is violated. Continue downward.

Heapify (build heap from array):

  1. Start from the last non-leaf node (n // 2 - 1).
  2. Sift down each node from that position to the root.
  3. Result: a valid heap in O(n) time (not O(n log n)).

Properties:

Property Value
Insert O(log n)
Extract min/max O(log n)
Peek min/max O(1)
Build heap O(n)
Space O(n)

Visualization highlights:

  • Blue nodes: default.
  • Yellow node: the node currently being sifted up or down.
  • Red node: node being swapped to restore heap property.

Trie

What it does: A tree-shaped data structure for storing strings where each edge represents a character. Strings sharing a prefix share tree nodes, making prefix-based operations (insert, search, autocomplete) very efficient.

Structure:

  • Root node: empty character.
  • Each node: a character, a map from character to child node, and an is_end flag marking the end of a stored word.

Operations:

Insert:

  1. Start at the root.
  2. For each character in the word: if a child with that character doesn't exist, create one.
  3. After the last character, set is_end = True on that node.

Search:

  1. Walk character by character from the root.
  2. If any character is missing, the word is not in the trie.
  3. If all characters are found and is_end is True on the last node, the word exists.

Autocomplete:

  1. Find the node representing the given prefix (same as search up to the prefix length).
  2. From that node, do a DFS collecting all nodes with is_end = True, building full strings as you go.

Delete:

  1. Recursively navigate to the word's last character.
  2. Unset is_end.
  3. Remove nodes that are now leaves and not part of other words (cleanup).

Properties:

Property Value
Insert O(m) where m = word length
Search O(m)
Autocomplete O(m + k) where k = number of results
Space O(ALPHABET_SIZE × n × m)

Visualization highlights:

  • Blue nodes: default.
  • Yellow node: currently active node (being inserted/searched).
  • Thicker border: end-of-word node (is_end = True).
  • Green node: word found.

Stack

What it does: A last-in, first-out (LIFO) collection. Think of a stack of plates: you always add to and remove from the top.

Operations:

Push: Add an element to the top of the stack. O(1).

Pop: Remove and return the top element. Raises an error if empty. O(1).

Peek: Return the top element without removing it. O(1).

Properties:

Property Value
Push O(1)
Pop O(1)
Peek O(1)
Space O(n)

Use cases: Function call stack, undo/redo, expression parsing, DFS iterative implementation, balanced parenthesis checking.

Visualization: Elements stacked vertically, bottom to top. The topmost element is highlighted as active during push/pop/peek operations.


Queue

What it does: A first-in, first-out (FIFO) collection. Think of a line at a store: new people join at the back, and service happens from the front.

Operations:

Enqueue: Add an element to the rear. O(1).

Dequeue: Remove and return the front element. Raises an error if empty. O(1).

Peek: Return the front element without removing it. O(1).

Properties:

Property Value
Enqueue O(1)
Dequeue O(1) amortized (O(n) worst with list shift)
Peek O(1)
Space O(n)

Use cases: BFS, task scheduling, print queues, producer-consumer buffers, event systems.

Visualization: Elements arranged horizontally, left to right. Front is on the left (dequeue side), rear on the right (enqueue side). The active element is highlighted during operations.


Implementation Notes

Snapshot System

The backend executes each algorithm completely and records every meaningful intermediate state as a snapshot — a plain dictionary containing the data needed to draw that frame. All snapshots for a single run are returned in a single HTTP response.

The frontend stores the snapshot array in memory and uses setInterval to step through them at the user-selected speed. This decouples animation speed from network latency.

Grid Convention

  • 0 = passable cell
  • 1 = wall/obstacle
  • Movement: 4-directional (N, S, E, W)
  • Grid size: 20 rows × 40 columns

Complexity Notation

  • n = number of elements in sorting/searching
  • V = number of vertices (grid cells) in pathfinding
  • E = number of edges (valid neighbor connections) in pathfinding
  • h = height of the BST
  • m = length of a word in Trie operations