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 hours of video content every minute.
- Data generation is increasing by approximately each year (Ababneh et al., 2021).
Hierarchical Structure of Data Types
Data structures are broadly categorized into two types:
- Primitive Data Types: Basic forms of data representation.
- Integer: Numeric data representing whole numbers from negative infinity to infinity (e.g., ).
- Float: Rational numbers ending with a decimal figure (e.g., ).
- String: A sequence of characters representing text (e.g., "#141 Rizal Street").
- Boolean/Bool: Holds one of two values: true or false.
- 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 Structure | Advantages | Disadvantages |
|---|---|---|
| Array | Quick inserts; Fast access if index is known | Slow search; Slow deletes; Fixed size |
| Stack | Last-in, first-out (LIFO) access | Slow access to other items |
| Queue | First-in, first-out (FIFO) access | Slow access to other items |
| Linked List | Quick inserts; Quick deletes | Slow search |
| Tree | Quick search/insert/delete (if balanced) | Deletion algorithm is complex |
| Graph | Best models real-world situations | Some 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 .
- Max Index: Calculated as .
- 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 elementgrades[4]is automatically initialized to ). - 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).
- Complete Initialization:
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 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:
- Data: The value stored in the node.
- 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 ), end, or a specific index. If index is , the new node points to the old head and becomes the new head.
- Deletion: If deleting index , the head is moved to
head->next, and the old head is deleted. For other indices, theprev->nextis linked tocurrent->nextbefore deletingcurrent.
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 (): Worst-case scenario.
- Big Omega (): Best-case scenario.
- Big Theta (): Tight bound for both cases.
Complexity Tables
Table: Time Complexities of Linear Data Structures
| Operation | Array (Static) | Stack/Queue | Linked List |
|---|---|---|---|
| Access (by index) | |||
| Search (unsorted) | |||
| Insertion (Beg/End) | / | ||
| Insertion (Middle) |
Table: Space Complexities
| Data Structure | Space Complexity | Explanation |
|---|---|---|
| Array | Requires contiguous memory for elements. | |
| Stack/Queue | Stores elements plus pointers/resizing overhead. | |
| Linked List | 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:
- 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.
- 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 aftersumreturns).
- Example:
- 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
| Algorithm | Best Time | Average Time | Worst Time | Space |
|---|---|---|---|---|
| Bubble Sort | ||||
| Quick Sort | ||||
| Merge Sort |
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 , it typically requires passes. In the first pass of
[6, 3, 5, 0], the value moves to the last position.
Quick Sort
- Strategy: Divide and Conquer using a pivot.
- Process:
- Select a pivot (first, last, middle, or random).
- Partitioning: Rearrange elements so values less than the pivot move to the left and values greater move to the right.
- 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 but requires extra auxiliary space.