Data Structures and Algorithms Study Notes

Core Contributors and Module Preface

  • Author: Melgine M. Bauat, MSIT
  • Content Editors: Alexander S. Cochanco, MSIT; Ruth G. Luciano, PhD
  • Format Editor: Rose Anne G. Cochanco, MSIT
  • Language Editor: Pamela DC. Dauz, EdD
  • Institution: College of Information and Communications Technology, Nueva Ecija University of Science and Technology
Educational Foundation

Data structures and algorithms serve as essential building blocks for information technology and computer science curricula. They are crucial for developing efficient software solutions and enable logical thinking to solve complex problems in fields such as software development, data analysis, and artificial intelligence. This module utilizes the C++ programming language to provide a practical context, offering hands-on experience in writing and optimizing code.

Introduction to Data Structures and Algorithms

Definitions and Concepts
  • Data Structure: Fundamental schemes for the efficient organization and manipulation of data (Goodrich, Tamassia, & Goldwasser, 2014). It is regarded as both a storage model and a set of operations that define how data is accessed, modified, and managed (Weiss, 2013).
  • Algorithms: A computational process that transforms input into output in a predictable and reliable way (Knuth, 1997). Algorithms are the backbone of computing, emphasizing efficiency by minimizing the use of memory, processing power, and time (Cormen et al., 2009).
Data Generation Context
  • The digital economy is propelled by data, often termed "the new oil" (Yang et al., 2016).
  • YouTube users upload over 500500 hours of video content every minute.
  • Data generation is increasing by approximately 40%40\% each year (Ababneh et al., 2021).
Hierarchical Structure of Data Types

Data structures are broadly categorized into two types:

  1. Primitive Data Types: Basic forms of data representation.
    • Integer: Numeric data representing whole numbers from negative infinity to infinity (e.g., 4,5,−14, 5, -1).
    • Float: Rational numbers ending with a decimal figure (e.g., 1.11,2.75,3.141.11, 2.75, 3.14).
    • String: A sequence of characters representing text (e.g., "#141 Rizal Street").
    • Boolean/Bool: Holds one of two values: true or false.
  2. Non-Primitive Data Structures: Built using primitive types to handle complex tasks.
    • Linear: Data elements arranged sequentially (Arrays, Linked Lists, Stacks, Queues).
    • Non-Linear: Data elements arranged in hierarchical or interconnected fashions (Trees, Graphs).
Comparison of Data Structure Characteristics
Data StructureAdvantagesDisadvantages
ArrayQuick inserts; Fast access if index is knownSlow search; Slow deletes; Fixed size
StackLast-in, first-out (LIFO) accessSlow access to other items
QueueFirst-in, first-out (FIFO) accessSlow access to other items
Linked ListQuick inserts; Quick deletesSlow search
TreeQuick search/insert/delete (if balanced)Deletion algorithm is complex
GraphBest models real-world situationsSome algorithms are slow and complex

Linear Data Structures: Arrays, Stacks, and Queues

One-Dimensional Arrays

An array stores a fixed-size sequential collection of elements of the same type in contiguous memory locations.

  • Indexing: Indexing always starts at 00.
  • Max Index: Calculated as Length of Array−1\text{Length of Array} - 1.
  • C++ Declaration and Initialization:
    • Complete Initialization: int grades[5] = { 85, 87, 84, 90, 88 }; (Size matches the number of elements).
    • Partial Initialization: int grades[5] = { 85, 87, 84, 90 }; (The remaining element grades[4] is automatically initialized to 00).
    • Declaration without Initialization: int grades[5]; (Values are indeterminate until explicitly assigned).
    • Dynamic Size Allocation: int* grades = new int[numSubjects]; (Allocates memory on the heap).
Two-Dimensional Arrays

Extends the concept to a matrix format using rows and columns, ideal for grids or image processing.

  • Example Declaration: int arr[2][3] = {{1, 2, 3}, {4, 5, 6}}; creates a 2×32 \times 3 matrix.
Queues

Follows the First-In-First-Out (FIFO) principle.

  • Operations:
    • Enqueue: Adding an element to the rear.
    • Dequeue: Removing an element from the front.
  • STL Queue Functions:
    • q.push(value): Adds an element.
    • q.pop(): Removes the front element.
    • q.front(): Retrieves the front element.
    • q.back(): Retrieves the rear element.
    • q.empty(): Returns true if the queue has no elements.
Stacks

Follows the Last-In-First-Out (LIFO) principle, visualized like a pile of cafeteria plates.

  • Operations:
    • Push: Adds an element to the top, which becomes the new top element.
    • Pop: Removes the top element and adjusts the pointer.
    • Peek/Top: Returns the top element without removing it.
    • isEmpty: Checks for elements to prevent errors during pop or peek.

Linked Lists

Components and Structure

A linked list consists of nodes that do not require contiguous memory. Each node contains:

  1. Data: The value stored in the node.
  2. Pointer/Link: A reference to the next node in the sequence.
Key Terms
  • Head/Root: The first node, serving as the entry point. If the list is empty, the head is nullptr.
  • Tail: The last node, where the pointer is null.
  • Node Structure in C++:
struct Node {
  string data;
  Node* next;
};
Types of Linked Lists
  • Singly Linked-List: Each node points only to the next node.
  • Doubly Linked-List: Each node contains three fields: data, a pointer to the next node, and a pointer to the previous node, allowing bidirectional traversal.
  • Circular Linked-List: The last node points back to the first node, forming a loop with no traditional "tail."
Node Operations
  • Insertion: Can occur at the beginning (index 00), end, or a specific index. If index is 00, the new node points to the old head and becomes the new head.
  • Deletion: If deleting index 00, the head is moved to head->next, and the old head is deleted. For other indices, the prev->next is linked to current->next before deleting current.

Complexity Analysis

Definitions
  • Time Complexity: The number of computational steps an algorithm takes as input size grows.
  • Space Complexity: The amount of memory used during runtime, including variables and pointers.
  • Asymptotic Notations:
    • Big O (OO): Worst-case scenario.
    • Big Omega (Ω\Omega): Best-case scenario.
    • Big Theta (Θ\Theta): Tight bound for both cases.
Complexity Tables

Table: Time Complexities of Linear Data Structures

OperationArray (Static)Stack/QueueLinked List
Access (by index)O(1)O(1)O(n)O(n)O(n)O(n)
Search (unsorted)O(n)O(n)O(n)O(n)O(n)O(n)
Insertion (Beg/End)O(n)O(n) / O(1)O(1)O(1)O(1)O(1)O(1)
Insertion (Middle)O(n)O(n)O(n)O(n)O(n)O(n)

Table: Space Complexities

Data StructureSpace ComplexityExplanation
ArrayO(n)O(n)Requires contiguous memory for elements.
Stack/QueueO(n)O(n)Stores elements plus pointers/resizing overhead.
Linked ListO(n)O(n)Stores data plus an additional pointer per node.

Recursion in C++

Mechanics of Recursion

Recursion occurs when a function calls itself, directly or indirectly. It requires two parts:

  1. Base Case: The simplest form of the problem that can be solved immediately to stop the recursion. Failure to have a base case results in a stack overflow.
  2. Recursive Case: The part where the function calls itself with modified arguments, moving closer to the base case.
Types of Recursion
  • Non-tail Recursion: The recursive call is not the last operation. Additional work (like addition or multiplication) is performed after the call returns.
    • Example: return no + sum(no - 1); (The addition happens after sum returns).
  • Tail Recursion: The recursive call is the final action. It can be optimized by compilers using Tail Call Optimization (TCO) to reuse stack frames and save memory.
Comparison with Iteration
  • Recursion: Often more elegant and intuitive for problems with self-similar structures (e.g., Tree traversal, Factorial, Fibonacci).
  • Iteration: Uses loop constructs (for, while). Generally more efficient as it avoids the overhead of multiple function calls and stack frame management.

Sorting Algorithms

Performance Overview
AlgorithmBest TimeAverage TimeWorst TimeSpace
Bubble SortO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)O(1)O(1)
Quick SortO(nlog⁡(n))O(n \log(n))O(nlog⁡(n))O(n \log(n))O(n2)O(n^2)O(log⁡(n))O(\log(n))
Merge SortO(nlog⁡(n))O(n \log(n))O(nlog⁡(n))O(n \log(n))O(nlog⁡(n))O(n \log(n))O(n)O(n)
Bubble Sort
  • Process: Repeatedly steps through the array, compares adjacent pairs, and swaps them if they are in the wrong order. Largest values "bubble" to the end.
  • Passes: In a list of size nn, it typically requires n−1n-1 passes. In the first pass of [6, 3, 5, 0], the value 66 moves to the last position.
Quick Sort
  • Strategy: Divide and Conquer using a pivot.
  • Process:
    1. Select a pivot (first, last, middle, or random).
    2. Partitioning: Rearrange elements so values less than the pivot move to the left and values greater move to the right.
    3. Recursively apply the same logic to sub-arrays.
  • Termination: The recursion terminates when a sub-array has zero or one element.
Merge Sort
  • Strategy: Divide and Conquer by splitting the array into halves until single-element sub-arrays exist.
  • Process: Merges sorted sub-arrays back together. It is stable and provides very consistent performance at O(nlog⁡(n))O(n \log(n)) but requires extra auxiliary space.