Comprehensive Study Notes: Data Structures and Algorithms
Foundations of Algorithms and Pseudocode Implementations
Methodology and Scope:
The provided material focuses on language-independent implementations of common and uncommon algorithms using pseudocode. This approach allows for easy porting to most imperative programming languages.
The implementations represent designs by the authors based on core concepts; they may differ from standard library implementations or normalization seen in other texts.
Algorithm analysis is conducted using abstract Big Oh notation to assess run time complexity, appealing to a broad audience without requiring formal mathematical proofs for every instance. It is recommended to use this material alongside texts containing formal proofs.
Assumed Knowledge:
Big Oh Notation: Essential for determining the best algorithm for specific scenarios based on run time complexity.
Imperative Programming: Proficiency in languages such as , , or Java is required to port the pseudo-imperative code. Functional programmers (Haskell, F#, OCaml) must adapt these logic patterns to the functional paradigm.
Object-Oriented (OO) Concepts: Understanding of inheritance, encapsulation, and polymorphism is necessary to appreciate the design of the data structures.
Virtual Machines: C# and Java target virtual machines providing garbage collection and security sandboxing. When porting to , references in pseudocode should be interpreted as pointers.
Big Oh Notation and Complexity Analysis
Growth as a Key Factor: Big Oh isolates growth as the primary factor in algorithm analysis, allowing for hardware-independent comparisons. A logarithmic algorithm will eventually outperform a quadratic algorithm as , regardless of the machine's speed.
Common Complexity Classes:
(Constant): Operations independent of input size, such as adding a node to the tail of a linked list with a tail pointer.
(Logarithmic): Algorithms that divide the problem into smaller chunks per invocation, such as searching a Binary Search Tree (BST).
(Linear): Run time is directly proportionate to input size .
(n log n): Algorithms that split problems into chunks and then stitch the results back together, such as Quick Sort.
(Quadratic): Often seen in algorithms with nested loops, like Bubble Sort.
(Cubic) and (Exponential): Extremely rare and highly inefficient. They should be avoided or reserved for very small problems. Enountering these should trigger a design review.
Pseudocode Standards and Conventions
Algorithm Structure:
All algorithms start with a signature:
algorithm AlgorithmName(arg1, arg2, ..., argN)and end withend AlgorithmName.Scope for loops and conditionals is explicitly closed (e.g.,
end if,end for,end while) to prevent ambiguity.
Contractual Conditions:
Pre-conditions: Requirements that must be met before execution (e.g., or parameters not being null). These are critical to algorithm operation.
Post-conditions: The state of the data or the result returned after the algorithm concludes (e.g., "The list has been sorted").
Parameter Inference:
Types are inferred from context. Variable usually denotes an integer equivalent to a WORD on a 32-bit machine. Variable often denotes a list or resizable array.
Keywords:
yield: Used similarly to return, but it returns each value to the caller sequentially. Control returns to the caller only when all values are exhausted.
Linked Lists
Structural Properties: Linked lists consist of a series of nodes where each node contains a value and at least one pointer/reference to another node.
Head and Tail Pointers: Maintaining both head and tail pointers allows for insertion at both ends.
Singly Linked List: Each node has a
Valueand aNextreference.Doubly Linked List: Each node has
Value,Next, andPreviousreferences.
Complexity Summary:
Insertion: for head or tail. For random insertion (middle of the list), the complexity is due to the need to traverse to the predecessor.
Deletion: in general, as the node must be found. If deleting specifically from the head, it is .
Searching: Always .
Traversal Techniques:
Forward Traversal: Start at the head and follow
Nextpointers until reaching .Singly Linked Reverse Traversal: Highly inefficient () because finding a predecessor for each node requires an scan from the head.
Doubly Linked Reverse Traversal: Efficiently performed by starting at the tail and following
Previouspointers.
Binary Search Trees (BST)
Organizational Rule: For a root node with value , the left subtree contains values and the right subtree contains values .
Complexity: If the tree is reasonably balanced, Insert, Lookup, and Deletion are . A pathologically unbalanced tree becomes a linked list with complexity.
Traversal Strategies:
Preorder: Visit root, then left subtree, then right subtree.
Postorder: Visit left subtree, then right subtree, then root.
Inorder: Visit left subtree, then root, then right subtree. This yields values in their sorted comparison order.
Breadth-First: Visit all nodes at a specific depth from left to right before moving to depth . Usually implemented using a queue.
Heaps
Definition: A tree-based structure generally implemented as an array. Heaps follow specific ordering strategies:
Min-Heap: The parent node's value is its children's values. The root is the minimum.
Max-Heap: The parent node's value is its children's values. The root is the maximum.
Array Mapping for Index :
Parent Index:
Left Child:
Right Child:
Operations:
Insert (): Add the value to the first free slot and invoke
MinHeapify(orMaxHeapify) to bubble the value up and restore order.Remove (): Find the target, replace it with the last element in the array, and then bubble that element down to restore order.
Search (): Involves a sequential scan of the array. Optimizations for
Containscan use the heap property to stop early if the target value falls outside the range of a level ( and for all at level ).
Sets
General Properties: Collections of unique, distinct values with no defined order. Notation: . Membership: .
Standard Operations:
Union (): Every element in or . Complexity: .
Intersection (): Elements present in both and . Complexity: where is the size of the smaller set.
Implementation Types:
Unordered Set: Backed by a Hash Table. Provides near insertion and lookup.
Ordered Set: Backed by a balanced tree like an AVL tree. Provides insertion and lookup, maintaining sorted order via inorder traversal.
Queues
First-In-First-Out (FIFO): The first item added is the first served.
Core Methods:
Enqueue: Place item at the back.
Dequeue: Remove and return the front item.
Peek (or Front): Return front item without removal.
Variations:
Standard Queue: Efficiently implemented with a singly linked list ( enqueue/dequeue).
Priority Queue: Items ordered by a comparer. Best implemented with a Heap; looking at the highest priority item is an check of index 0.
Double Ended Queue (Deque): Allows access to both front and back. Usually implemented with a doubly linked list to avoid array resizing costs.
AVL Trees
Self-Balancing Property: Invented by Adelson-Velsky and Landis. The height difference (Balance Factor) between left and right subtrees of any node is at most . This ensures height.
Tree Rotations (): Constant-time operations to restore balance by moving subtrees up or down.
Left Rotation: Triggered when a right subtree is too heavy.
Right Rotation: Triggered when a left subtree is too heavy.
Double Rotations:
LeftAndRightRotationandRightAndLeftRotationhandle cases where a single rotation is insufficient.
Sorting Algorithms
Bubble Sort (): Repeatedly compares and swaps adjacent elements.
Merge Sort (): A divide-and-conquer algorithm. Splits the list until size 1, then merges sorted sub-lists using a
MergeOrderedhelper.Quick Sort (): Uses a pivot to partition the list into
less,equal, andgreatersub-lists. Median-value pivot selection is ideal to avoid worst-case performance.Insertion Sort (): Builds a sorted sequence one item at a time, similar to sorting a hand of playing cards.
Shell Sort (): A variation of insertion sort that compares items at varying distances (increments).
Radix Sort: Uses buckets (queues) to sort items by individual digits (keys). Requires isolating keys: .
Numeric Algorithms
Primality Test: Checks if is prime by iterating from up to .
Greatest Common Denominator (GCD): Euclid's algorithm used to find the largest multiple of two integers using recursion:
GreatestCommonDenominator(n, m % n).Base Max Value: The maximum value for a base with digits is calculated as .
Example: Hexademical (Base 16) with 6 digits is ().
Factorial (): Iterative implementation is preferred over recursive to avoid overhead. . For , .
Searching Algorithms
Sequential Search (): Basic linear loop through a list.
Probability Search (): A variation of sequential search that swaps a found item with its predecessor. This increases the probability that frequently accessed items move to the front of the list, reducing average scan time.
String Algorithms
Reverse Words: Uses a string buffer to rebuild the sentence by identifying word boundaries (white space) and marching backwards from the end of the string.
Palindrome Detection (): Uses two pointers at the
leftandrightends of a stripped, uppercase string. Pointers move inward as long as characters match.Word Counting: Uses a Boolean flag
inWordto track the state transitions between white space and characters to handle multiple spaces between words.Repeated Word Count: Splits a string into an array, adds each stripped word to a Set, and subtracts the Set's total count from the array's total length.
Any Character Match (): Determines if any character in one string exists in another using a nested double loop.
Practical Implementation Tips
Verification: Work through algorithms manually with pen and paper using a variable mutation table to track state change.
Recursion Warning: Use recursion for tree structures but be cautious of overhead in linear or quadratic logic.
Memory Management: In managed languages (, Java), nullify references in data structures (like Heaps) after deletion so the garbage collector can reclaim memory.