Data Structures and Algorithms - Comprehensive Study Guide
Course Overview & Syllabus
Course Code: ICT1305 / ICT1403 – Data Structures
Lecturer: P.S. Palliyaguruge
Course Syllabi:
Data Structures: Random Access and Sequential access, Performance Analysis, Big O notation, Arrays, Array-based Lists, Linked Lists (Array-Based, Singly Linked, Doubly Linked, Circular, Sorted), Stacks using Arrays and Linked Lists, Queues using Arrays and Linked Lists, Hash Tables using Arrays and Linked Lists, Trees using Arrays and Linked Lists, Graphs (Depth First Search, Breadth First Search).
Simple Sorting & Searching Algorithms: Selection sort, Bubble sort, Merge sort, Binary search.
Recommended References:
Algorithms, Data Structures, and Problems - Addison Wesley
Data Structures, Algorithms, And Object Oriented Programming – Gregory L. Heileman
Waite Group's Object-Oriented Programming in C++, Robert Lafore
Fundamentals of Data Structures in C++
Intended Learning Outcomes:
Demonstrate applications of different Data Structures.
Identify advantages and disadvantages of different Data Structures.
Demonstrate knowledge of various common algorithms.
Select appropriate Data Structures in developing computer applications.
Course Prerequisites:
Principle of Program Design and Programming – ICT1402
Data types
Structures in C
Arrays
Pointers
Functions
File handling
Software Engineering Context
Software Engineering Definition: The study of ways in which to create large and complex computer applications (involving many programmers and designers) based on the needs and requirements of end users.
Software Development Life Cycle (SDLC) Stages:
Specification
Requirements gathering
Design
Verification
Coding
Testing
Quality assurance
User acceptance testing
Production
Ongoing maintenance
Data Structures in the SDLC:
An in-depth understanding of every single component of software engineering is not mandatory.
The study of data structures and algorithms is directly concerned with the coding phase.
Data structures and algorithms serve as the fundamental "nuts-and-bolts" used by programmers to store and manipulate data effectively.
Fundamentals of Data Structures
Core Definitions:
Data structures are ways in which data are arranged in computer memory or stored on a hard disk.
In computer science, a data structure is a way of storing data in a computer so that it can be used efficiently.
Operational Efficiency:
A carefully chosen data structure allows a more efficient algorithm to be executed.
A well-designed data structure allows a variety of critical operations to be performed using as few computational resources (execution time and memory space) as possible.
Examples of Data Structures: Arrays, linked lists, stacks, queues, trees, graphs, tables, files.

Abstract Data Types (ADT) & Data Abstraction
Abstract Data Type (ADT) Definition: In computing, an Abstract Data Type (ADT) is a specification of a set of data and the set of operations that can be performed on that data.
Principles of Data Abstraction:
Viewing a data structure by focusing strictly on what it does while ignoring how it does its job.
Real-World Abstraction Example:
The
doubledata type is an abstraction of real numbers.Physical computer hardware limits the maximum range and precision of real numbers that can be represented.
Different computer architectures use a variety of internal representation schemes for type
double.Programmers utilize
doubleand its associated operators (+,-,*,/,=,==,<, etc.) without needing to concern themselves with low-level implementation details.
Interface vs. Implementation:
An abstract definition is independent of various concrete implementations.
Definitions can be expressed mathematically or programmed explicitly as an interface.
Interface Structure: Provides a constructor (which returns an abstract handle to new data) and several operations (functions accepting the abstract handle as an argument).
Implementation Decoupling Example: Stacks and queues are ADTs. Both can be implemented using arrays or linked lists, illustrating that their abstract conceptual definition is completely separate from their storage implementation.
Algorithms & Computational Complexity
Algorithm Definition: An algorithm is a procedure (a finite set of well-defined instructions) for accomplishing a task that, given an initial state, will terminate in a defined end-state.
Interrelationship with Data Structures:
Algorithms manipulate data stored within data structures (e.g., searching, sorting).
Computational complexity and efficient algorithm implementation depend directly on choosing suitable data structures.
Primary Categories of Algorithmic Operations:
Searching for a specific data item or record.
Sorting data (classified into Simple sorting and Advanced sorting).
Iterating through all items in a data structure (visiting each item in turn to display it or perform specific actions).
Inserting new data items.
Deleting specified data items.
Practical Applications of Data Structures & Algorithms
Real-World Data Storage:
Stores data describing physical entities external to the computer system.
Examples: Personnel records, stacks of index cards.
Programmer Tools:
Data structures that are not intended for direct access by end-users, but are used internally by the program itself to facilitate execution.
Real-World System Modeling:
Data structures that directly model real-world scenarios and physical networks.
Examples:
Graphs: Used to represent airline flight routes and task dependencies in project management.
Queues: Used to represent patient queues in medical clinics or customer service lines.
Asymptotic Analysis & Big O Notation
Evaluating Algorithmic Efficiency:
A single computational problem often has numerous algorithmic solutions.
Choosing the optimal algorithm requires evaluating running time and computational work.
Comparative metrics must evaluate performance relative to the number of input items , rather than relying on hardware-specific timing.
Asymptotic Complexity Definition: A method of expressing the primary growth component of an algorithm's cost using idealized units of computational work.
Big O Notation Definition: A mathematical notation used to describe the asymptotic behavior of functions, characterizing a function's behavior for very large (or very small) inputs in a simple and rigorous manner that enables direct comparison to other functions.


Time Complexity Calculations for Fundamental Operations:
Insertion into an Unordered Array:
Time taken to insert an item is constant and independent of the total item count .
Mathematical formulation: , corresponding to .
Linear Search:
Time taken is proportional to half the total number of items .
Mathematical formulation: , corresponding to .
Binary Search:
Time taken is proportional to .
Mathematical formulation: , corresponding to .
Comparative Analysis: Multiplying an -Digit Number by an -Digit Number:
Method 1: Repeated Additions
Requires a maximum of addition operations (since the maximum value of an -digit number is ).
Method 2: Digit-by-Digit Multiplication (using multiplication tables)
Requires a maximum of operations.
Operation Comparison Table for :
For : Repeated Additions vs. Digit Multiplication
For : Repeated Additions vs. Digit Multiplication
For : Repeated Additions vs. Digit Multiplication
For : Repeated Additions vs. Digit Multiplication
C / C++ Background Review
Input and Output:
printf/scanfheader<stdio.h>.Conditional Expressions:
if,if..else.Control Structures:
for,while.File Input/Output: Standard file management via
<stdio.h>.Functions: Parameter passing methods, pointers to functions, and recursive functions.
Pointers and Dynamic Memory Allocation:
Pointer Definition: A special variable type that stores the memory address of another variable, essential for dynamic memory allocation.
Memory Management in C:
c int *num, *data; data = (int *)malloc(sizeof(int) * 10); num = data; free(data); Memory Management in C++:
cpp int *num, *data; data = new int[10]; num = data; delete[] data;
Classification of Data Structures
Primitive Data Structures: Basic types built into the language.
Examples: Integer, Real, Character, Pointer, Logical.
Non-Primitive Data Structures: Complex structures built from primitive data types.
Linear Data Structures: Elements are organized sequentially.
Static: Array.
Dynamic: Linear List, Linked List, Stack, Queue.
Non-Linear Data Structures: Elements are organized hierarchically or arbitrarily.
Examples: Tree, Graph.

Arrays
Definition: Derived data types that store a group of homogeneous elements under a single name in contiguous memory locations.
Structural Properties:
Contiguous Storage: Elements are located in consecutive memory cells, making access faster.
Direct Indexing: Elements are accessed via position references (index).
Dimensionality: Can be multi-dimensional (most practical applications require a maximum of 3 dimensions).
Declaration & Indexing in C/C++:
Declaration syntax:
int var_name[50];(declares an integer array with maximum size = 50).Zero-Based Indexing: Positions start at
0and end at positionn - 1.Code Example:
cpp var_name[0] = 0; var_name[1] = 1; var_name[2] = 30; cout << "var_name[0] =" << var_name[0];
Advantages & Disadvantages:
Advantages:
Quick insertion at the end of the array.
Very fast random access () when the index is known.
Disadvantages:
Slow search ( for unsorted arrays).
Slow deletion () due to shifting elements to close memory gaps.
Fixed memory size set at declaration time.
Pointers & Arrays Relationship
Pointer Syntax:
dataType *variableName;ordataType* variableName;.Pointer Operations:
Example:
float *ptrX;where*ptrXdereferences to a float value, andptrXholds the memory address.Pointer Arithmetic:
ptrX + 1moves the pointer to the next memory address block based on data type size;*ptrX + 1adds 1 to the dereferenced value.
Relationship to Arrays:
The name of an array acts as a pointer to the memory location of its first element (
&array[0]).Equivalent Pointer Allocation Example:
cpp int *num, *data; data = new int[10]; num = data; delete[] data;
Abstract Lists & Array Implementations
Formal Definition of List: A sequence of zero or more elements of a given type represented as where . is the first element, and is the last element.
Core Characteristics:
Flexible structure capable of growing or shrinking on demand.
Elements can be accessed, inserted, or deleted at any position.
Lists can be concatenated or split.
Application Domains: Information retrieval systems, programming language translation/compilers, systems simulation.
Array Implementation of Lists:
Elements are stored in contiguous array cells.
Sequential traversal is straightforward.
Appending elements to the tail is efficient ().
Inserting an element into the middle requires shifting existing elements one position to the right ().
Deleting any element except the last requires shifting subsequent elements to the left to fill the gap ().
Linked Lists
Fundamental Properties:
A dynamic ordered n-tuple consisting of a sequence of nodes.
Each node contains arbitrary data fields and one or two references (links) pointing to next and/or previous nodes.
Self-referential data type containing a pointer/link to another node of the same type.
Allows node addition or deletion at any location without relocating other nodes.
Sequential element access.
C Language Structure Definitions
Node Structure Definition:
struct listNode {
int data;
struct listNode *link; // Address of the next node
};
```
- LinkedList Container Definition:
c struct linkedList { struct listNode head; / First element of the list / int length; / Number of items */ }; ```
C Function Implementations
List Initialization Routine:
struct linkedList* initList() {
struct linkedList *L = malloc(sizeof(struct linkedList));
L->head = NULL;
L->length = 0;
return L;
}
```
- End Insertion Method ( Unoptimized Scan):
c void insert(int newData, struct linkedList *L) { struct listNode *newNode = malloc(sizeof(struct listNode)); newNode->data = newData; newNode->next = NULL; if (L->head == NULL) { L->head = newNode; } else { struct listNode *scan = L->head; while (scan->next != NULL) { scan = scan->next; } scan->next = newNode; } L->length++; } ```
Node Deletion Function:
void deleteItem(int Ddata, struct linkedList *L) {
struct listNode *scan1 = L->head;
if (scan1 != NULL && scan1->data == Ddata) {
L->head = L->head->next;
free(scan1);
L->length--;
} else {
struct listNode *scan2 = scan1;
while (scan1 != NULL && scan1->data != Ddata && scan2->next != NULL) {
scan1 = scan2;
scan2 = scan2->next;
}
if (scan2 != NULL && scan2->data == Ddata) {
scan1->next = scan2->next;
free(scan2);
L->length--;
} else {
printf("
Item not found");
}
}
}
```
- Traversal and Display Routine:
c void display(struct linkedList L) { struct listNode *current = L.head; while (current != NULL) { printf("%d ->", current->data); current = current->next; } printf("End . "); } ```
Sorted Linked Lists
Definition: A linked list in which data elements are inserted in ascending order of their key values.
Formal Ordering Condition: If and are two nodes such that , then .
Linked Lists vs. Arrays Comparison
Operational Efficiency Comparison:
Indexing / Random Access: Array vs. Linked List
Inserting / Deleting at End: Array vs. Linked List (with tail pointer) or (without tail pointer)
Inserting / Deleting in Middle (given node pointer): Array vs. Linked List
Persistent Data Structure Capability: Array = No; Singly Linked List = Yes
Locality of Reference (Cache efficiency): Array = Great; Linked List = Bad
Trade-off Analysis:
Dynamic Capacity: Linked lists expand continuously until system memory is exhausted; arrays fill up or require costly reallocation/copying.
Access Paradigm: Arrays support random access; linked lists permit only sequential access.
Traversal Direction: Singly linked lists can only be traversed in one direction.
Memory Overhead: Linked lists require extra memory per node for storing pointer references.
Linked List Structural Variants
Singly-Linked List (Linearly-Linked List):
Simplest linked list variant containing one pointer per node pointing to the next node or NULL.
Doubly-Linked List:
Each node contains two links:
prev(points to the previous node or NULL) andnext(points to the next node or NULL).Advantages: Allows bidirectional sequential access; nodes can be inserted or deleted in constant operations given only that node's memory address.
Disadvantages: Requires additional storage per node; elementary operations require updating more pointers; cannot be used as persistent data structures.
Circularly-Linked Lists:
The first and final nodes are linked together, forming a continuous ring without explicit start or end boundaries.
Can be constructed as Singly-Circular or Doubly-Circular lists.
Characteristics: Traversal can begin at any arbitrary node; provides quick access to both first and last records through a single tail pointer; ideal for modeling naturally circular systems and processes.