Source status: The TU 2025 PDF lists BCA201 in semester 3 but does not publish a detailed unit outline there. The units and explanations below are BCA Nepal study material adapted from an earlier course outline. Confirm current topics with your instructor.
Course code: BCA201 (earlier catalog: CACS201)
Semester: 3
Credits: 3
Class load: 6 Hrs./Week (Theory: 3 Hrs., Practical: 3 Hrs.)
Course Overview
Data Structure and Algorithm is the backbone course of computer science. It answers a single practical question: given a problem and data, what is the most efficient way to organize and process that data? Every piece of software you write depends on these choices. A social network stores friendships as a graph; a web browser uses a stack to track visited pages; a database uses a B-tree for fast lookup. This course develops the vocabulary and tools to make those choices deliberately.
By the end of the course you will be able to describe how each data structure stores items internally, what operations it supports, how fast those operations are in the worst case, and when to prefer one structure over another. You will also practice translating real problems into algorithm steps and reasoning about correctness.
Learning Outcomes
- Define data structure, ADT, and algorithm and explain the relationship between them.
- Implement stacks and queues using arrays and linked lists, and apply them to expression evaluation.
- Build singly and doubly linked lists with insertion, deletion, and traversal.
- Write recursive solutions for factorial, Fibonacci, Tower of Hanoi, and tree traversal.
- Implement binary search trees and perform pre-order, in-order, and post-order traversals.
- Apply and compare insertion sort, selection sort, bubble sort, quick sort, merge sort, heap sort, shell sort, and radix sort.
- Implement sequential search, binary search, and hashing with collision resolution.
- Represent graphs as adjacency matrices and adjacency lists, and apply BFS, DFS, Dijkstra, and Kruskal algorithms.
- Analyze algorithm efficiency using Big-O notation and distinguish O(1), O(log n), O(n), O(n log n), and O(n²).
- Select the appropriate data structure and algorithm for a given problem scenario.
Unit 1: Introduction to Data Structure
Teaching hours: 2
1.1 Definition
A data structure is a way of organizing, managing, and storing data in a computer so that operations on that data — inserting, deleting, searching, traversing — can be performed efficiently. The word "structure" is key: it refers to the layout and relationships among data items, not just the items themselves.
A simple example: storing 1000 student marks in an array lets you jump directly to index 42 in a single step. Storing the same marks in a plain text file and scanning line by line makes the same operation take 42 steps. The array is a data structure that makes random access O(1).
Data structures are divided into:
| Type | Examples |
|---|---|
| Primitive | int, float, char, bool — directly supported by the hardware |
| Non-primitive linear | Array, Stack, Queue, Linked List |
| Non-primitive non-linear | Tree, Graph |
1.2 Abstract Data Type (ADT)
An Abstract Data Type separates what a data structure does from how it does it. The ADT defines:
- The domain (the set of values it stores)
- The operations (what you can do with those values)
- The behaviour of each operation (what it returns, what preconditions are needed)
The ADT says nothing about memory layout, language, or implementation.
Example — Stack ADT:
ADT Stack {
Operations:
push(item) — add item to top
pop() — remove and return top item
peek() — return top item without removing
isEmpty() — return true if stack has no items
isFull() — return true if stack is at capacity
}
This ADT is the same whether you implement the stack with an array or a linked list.
Why ADTs matter: They let you design algorithms at the conceptual level first, then choose the best concrete implementation. When you later switch from an array-based stack to a linked-list stack, the algorithm using the stack does not need to change.
1.3 Importance of Data Structures
- Performance: The right data structure reduces time and memory usage. Binary search on a sorted array finds an item in O(log n) steps; a linear scan takes O(n).
- Code clarity: A well-chosen structure makes the algorithm's intent obvious.
- Scalability: Structures like hash tables and B-trees maintain fast operations as data grows to millions of records.
- Foundation for algorithms: Sorting, graph traversal, dynamic programming — all depend on specific data structures.
Key Terms — Unit 1
- Data structure — organized collection of data with defined relationships
- ADT — specification of data and operations, independent of implementation
- Linear structure — elements arranged in sequence (array, list, stack, queue)
- Non-linear structure — elements with hierarchical or networked relationships (tree, graph)
- Algorithm — a finite, precise sequence of steps that solves a problem
Unit 1 Summary
Data structures are the foundation of efficient software. An ADT describes behaviour without specifying implementation. The choice of structure determines how fast programs run and how clearly they express intent.
Unit 1 Practice Questions
Q1. Distinguish between a data structure and an ADT. (ADT is the specification; data structure is the implementation.)
Q2. Why is an array considered a primitive data structure by some authors but non-primitive by others? (Arrays are built into languages and hardware, but they group multiple values, so classification varies by textbook.)
Q3. Give one real-world scenario where choosing the wrong data structure would cause performance problems. (Storing a phone book in an unsorted linked list makes lookup O(n); a hash table would make it O(1).)
Unit 2: The Stack
Teaching hours: 3
2.1 Introduction and ADT
A stack is a linear data structure that follows LIFO — Last In, First Out. The last item pushed onto the stack is the first item popped off. Think of a stack of cafeteria trays: you add a tray on top and also take from the top.
Core operations:
| Operation | Description | Returns |
|---|---|---|
push(item) |
Add item to the top | — |
pop() |
Remove and return the top item | item |
peek() / top() |
Return top item without removing | item |
isEmpty() |
Check if stack is empty | bool |
isFull() |
Check if stack is full (array impl.) | bool |
Conditions:
- Pushing onto a full stack causes stack overflow.
- Popping from an empty stack causes stack underflow.
Array implementation in C:
#define MAX 100
int stack[MAX];
int top = -1; // -1 means empty
// Push
void push(int val) {
if (top == MAX - 1) {
printf("Stack overflow\n");
return;
}
stack[++top] = val; // increment top, then store
}
// Pop
int pop() {
if (top == -1) {
printf("Stack underflow\n");
return -1;
}
return stack[top--]; // return top item, then decrement
}
// Peek
int peek() {
if (top == -1) return -1;
return stack[top];
}
2.2 POP and PUSH Operations (Detailed trace)
Trace of push(10), push(20), push(30), pop():
Initial: top = -1, stack = []
push(10): top = 0, stack = [10]
push(20): top = 1, stack = [10, 20]
push(30): top = 2, stack = [10, 20, 30]
pop(): returns 30, top = 1, stack = [10, 20]
peek(): returns 20, top = 1 (unchanged)
2.3 Stack Application: Expression Evaluation and Conversion
Stacks are the standard tool for evaluating arithmetic expressions because they handle operator precedence and parentheses naturally.
Expression notations:
| Notation | Form | Example |
|---|---|---|
| Infix | Operator between operands | A + B * C |
| Prefix (Polish) | Operator before operands | + A * B C |
| Postfix (Reverse Polish) | Operator after operands | A B C * + |
Converting Infix to Postfix (Shunting-Yard algorithm)
Operator precedence: * and / > + and -; left-associative.
Rules:
- If the token is an operand, output it.
- If the token is
(, push it onto the stack. - If the token is
), pop and output until(is found; discard(. - If the token is an operator, pop and output operators with higher or equal precedence, then push the new operator.
- At the end, pop and output all remaining operators.
Example: Convert A + B * C - D to postfix.
Token Stack (bottom→top) Output
A [] A
+ [+] A
B [+] A B
* [+, *] A B
C [+, *] A B C
- [−] A B C * + (pop * then +, then push -)
D [−] A B C * + D
end [] A B C * + D -
Result: A B C * + D -
Evaluating a Postfix Expression
Rules:
- If the token is an operand, push it.
- If the token is an operator, pop two operands, apply the operator, push the result.
Example: Evaluate 5 3 2 * + 1 -
Token Stack
5 [5]
3 [5, 3]
2 [5, 3, 2]
* [5, 6] (3 * 2 = 6)
+ [11] (5 + 6 = 11)
1 [11, 1]
- [10] (11 - 1 = 10)
Result: 10
Key Terms — Unit 2
- LIFO — Last In, First Out
- Stack overflow — push on full stack
- Stack underflow — pop from empty stack
- Infix / Prefix / Postfix — expression notation forms
Unit 2 Practice Questions
Q1. Convert (A + B) * (C - D) to postfix using a stack trace. (Result: A B + C D - *)
Q2. Evaluate the postfix expression 6 2 / 3 + 4 2 - *. (6/2=3; 3+3=6; 4-2=2; 62=12 → result 12)*
Q3. What is the difference between peek and pop? (pop removes the top; peek reads it without removing)
Unit 3: Queue
Teaching hours: 3
3.1 Introduction and ADT
A queue is a linear data structure following FIFO — First In, First Out. The first item added is the first item removed. Real-world analogy: a ticket counter line.
Core operations:
| Operation | Description |
|---|---|
enqueue(item) |
Add item to the rear |
dequeue() |
Remove and return item from the front |
front() |
Return front item without removing |
isEmpty() |
True if queue is empty |
isFull() |
True if queue is at capacity |
3.2 Linear Queue
In an array-based linear queue, front starts at 0 and rear advances on each enqueue. When rear reaches the end of the array, the queue appears full even if positions at the beginning (freed by dequeue) are unused. This wastes memory.
Enqueue 10: front=0, rear=0 → [10, _, _, _]
Enqueue 20: front=0, rear=1 → [10, 20, _, _]
Dequeue: front=1, rear=1 → [_, 20, _, _] (10 removed)
Enqueue 30: front=1, rear=2 → [_, 20, 30, _]
3.3 Circular Queue
A circular queue wraps the array around. rear = (rear + 1) % MAX and front = (front + 1) % MAX. This reuses freed positions.
#define MAX 5
int queue[MAX];
int front = 0, rear = 0, count = 0;
void enqueue(int val) {
if (count == MAX) { printf("Full\n"); return; }
queue[rear] = val;
rear = (rear + 1) % MAX;
count++;
}
int dequeue() {
if (count == 0) { printf("Empty\n"); return -1; }
int val = queue[front];
front = (front + 1) % MAX;
count--;
return val;
}
Trace — circular queue of size 4:
enqueue(A): front=0, rear=1, [A,_,_,_]
enqueue(B): front=0, rear=2, [A,B,_,_]
dequeue(): returns A, front=1, [_,B,_,_]
enqueue(C): front=1, rear=3, [_,B,C,_]
enqueue(D): front=1, rear=0, [_,B,C,D] (rear wraps to 0)
enqueue(E): front=1, rear=1, [E,B,C,D] (position 0 reused)
3.4 Priority Queue
A priority queue extends the queue concept: each item has a priority, and dequeue always removes the highest-priority item regardless of arrival order. Used in Dijkstra's algorithm, OS process scheduling, and event simulations.
Two common implementations:
- Sorted array/list: Insert in sorted order (O(n) insert, O(1) dequeue)
- Binary heap: O(log n) insert, O(log n) dequeue
Key Terms — Unit 3
- FIFO — First In, First Out
- Circular queue — rear wraps around to position 0 when it reaches the end
- Priority queue — dequeue always removes highest-priority item
Unit 3 Practice Questions
Q1. Trace a circular queue of size 3 through: enqueue(X), enqueue(Y), enqueue(Z), dequeue(), enqueue(W). (After dequeue X, enqueue W uses the freed slot.)
Q2. Why is a circular queue preferred over a linear queue in practice? (Reuses freed slots, eliminating false-full conditions.)
Unit 4: List
Teaching hours: 2
4.1 Introduction
A list is an ordered collection of elements. Unlike stacks and queues, a list allows insertions and deletions at any position and direct access by index (for array-based lists).
4.2 Static vs. Dynamic List
| Feature | Static (Array) | Dynamic (Linked) |
|---|---|---|
| Size | Fixed at compile time | Grows/shrinks at runtime |
| Memory | Contiguous block | Scattered nodes, each with pointer |
| Random access | O(1) by index | O(n) — must traverse from head |
| Insert/Delete (middle) | O(n) — shift elements | O(1) if pointer is known |
| Memory waste | Pre-allocated slots may be unused | Each node has pointer overhead |
4.3 Array Implementation of Lists
An array list stores elements at indices 0…size−1 and tracks a length variable.
#define MAX 100
int list[MAX];
int length = 0;
// Insert at position pos
void insert(int pos, int val) {
for (int i = length; i > pos; i--)
list[i] = list[i-1]; // shift right
list[pos] = val;
length++;
}
// Delete at position pos
void delete(int pos) {
for (int i = pos; i < length - 1; i++)
list[i] = list[i+1]; // shift left
length--;
}
Pitfall: When inserting near the beginning of a large array, shifting all elements right takes O(n) time.
4.4 Queue as a List
A queue can be implemented as a list restricted to two operations: append to the end (enqueue) and remove from the beginning (dequeue). This is equivalent to the queue ADT defined in Unit 3.
Key Terms — Unit 4
- Static list — fixed-size array
- Dynamic list — grows and shrinks; typically a linked list
- Random access — accessing any element in O(1) using an index
Unit 5: Linked Lists
Teaching hours: 5
5.1 Introduction and ADT
A linked list is a chain of nodes where each node stores a data value and a pointer to the next node. Unlike an array, nodes are not stored in contiguous memory.
[data|next] → [data|next] → [data|next] → NULL
head tail
Advantages over arrays:
- Dynamic size — no pre-allocation needed
- O(1) insert/delete at known position (no shifting)
Disadvantages:
- No random access — finding element at index n costs O(n)
- Extra memory for pointers
5.2 Node Structure in C
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL; // empty list
5.3 Dynamic Implementation — Insert and Delete
Insert at beginning:
void insertFront(int val) {
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = head; // point new node to old head
head = newNode; // new node becomes head
}
Insert at end:
void insertEnd(int val) {
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = NULL;
if (head == NULL) { head = newNode; return; }
struct Node* cur = head;
while (cur->next != NULL) cur = cur->next; // walk to tail
cur->next = newNode;
}
Delete a node with given value:
void deleteNode(int val) {
if (head == NULL) return;
if (head->data == val) {
struct Node* temp = head;
head = head->next;
free(temp);
return;
}
struct Node* cur = head;
while (cur->next != NULL && cur->next->data != val)
cur = cur->next;
if (cur->next != NULL) {
struct Node* temp = cur->next;
cur->next = temp->next; // skip the node
free(temp);
}
}
5.4 Linked Stacks and Queues
A stack can be implemented as a linked list where push adds to the head and pop removes from the head. A queue can be implemented where enqueue adds to the tail and dequeue removes from the head. Both operations are O(1) with linked lists (no overflow condition).
5.5 Doubly Linked List
A doubly linked list adds a prev pointer to each node.
struct DNode {
int data;
struct DNode* prev;
struct DNode* next;
};
NULL ← [data|prev|next] ↔ [data|prev|next] ↔ [data|prev|next] → NULL
head tail
Advantages over singly linked list:
- Traverse in both directions
- Delete a node in O(1) given only a pointer to it (no need to find its predecessor)
- Implement deque (double-ended queue)
Disadvantages:
- Two pointers per node — 50% more pointer memory
Key Terms — Unit 5
- Node — data + pointer(s)
- Head — pointer to the first node
- Singly linked list — each node has one next pointer
- Doubly linked list — each node has prev and next pointers
Unit 5 Practice Questions
Q1. What happens to memory if you delete a node from a linked list in C without calling free()? (Memory leak — the node's memory remains allocated but unreachable.)
Q2. Compare time complexity of inserting at the beginning: array vs. linked list. (Array: O(n) due to shifting; linked list: O(1).)
Unit 6: Recursion
Teaching hours: 4
6.1 Introduction
Recursion is a programming technique where a function calls itself to solve a smaller version of the same problem. Every recursive function has two parts:
- Base case — the simplest input, solved directly without a recursive call.
- Recursive case — reduces the problem toward the base case and calls itself.
Without a base case, recursion never stops → infinite recursion → stack overflow.
6.2 Principle of Recursion
Three laws of recursion:
- A recursive algorithm must have a base case.
- A recursive algorithm must change its state toward the base case.
- A recursive algorithm must call itself.
6.3 Recursion vs. Iteration
| Feature | Recursion | Iteration |
|---|---|---|
| Mechanism | Function calls itself | Loop repeats |
| Stack usage | Each call uses a stack frame | No extra stack usage |
| Code size | Often shorter | May be longer |
| Performance | Function call overhead | Generally faster |
| Readability | Elegant for inherently recursive problems | Natural for sequential repetition |
Rule of thumb: Use recursion when the problem definition is inherently recursive (e.g., tree traversal). Use iteration for simple counting loops.
6.4 Recursion Examples
Factorial
long factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // recursive case
}
Trace — factorial(4):
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * 2 * factorial(1)
= 4 * 3 * 2 * 1 * factorial(0)
= 4 * 3 * 2 * 1 * 1
= 24
Fibonacci Series
int fib(int n) {
if (n == 0) return 0; // base case 1
if (n == 1) return 1; // base case 2
return fib(n-1) + fib(n-2);
}
Warning: Naive recursive Fibonacci is O(2ⁿ) — it recalculates subproblems. Use memoization or iteration for large n.
Tower of Hanoi (TOH)
Move n disks from peg A to peg C using peg B, never placing a larger disk on a smaller one.
void hanoi(int n, char from, char to, char via) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
hanoi(n-1, from, via, to); // move n-1 disks to via
printf("Move disk %d from %c to %c\n", n, from, to);
hanoi(n-1, via, to, from); // move n-1 disks from via to to
}
Trace — hanoi(3, A, C, B):
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Total moves = 2ⁿ − 1 = 7 for n = 3.
6.5 Applications of Recursion
- Tree and graph traversal
- Quick sort and merge sort
- Backtracking (solving mazes, N-Queens)
- Parsing expressions
Key Terms — Unit 6
- Base case — terminating condition
- Stack frame — memory allocated per function call
- Tower of Hanoi — classic recursive puzzle, 2ⁿ−1 moves
- Memoization — caching recursive subresults to avoid recomputation
Unit 7: Trees
Teaching hours: 5
7.1 Introduction
A tree is a non-linear hierarchical data structure consisting of nodes connected by edges. Every tree has exactly one root (topmost node). Each node can have zero or more children; a node with no children is a leaf.
Key terms:
| Term | Definition |
|---|---|
| Root | Topmost node; has no parent |
| Parent | Node directly above a child |
| Child | Node directly below a parent |
| Leaf (external node) | Node with no children |
| Internal node | Node with at least one child |
| Edge | Connection between parent and child |
| Height of a node | Longest path from node to a leaf |
| Depth of a node | Length of path from root to the node |
| Height of tree | Height of the root node |
| Level | All nodes at the same depth |
7.2 Binary Tree
A binary tree restricts each node to at most two children: left child and right child.
[10] ← root (level 0)
/ \
[5] [15] ← level 1
/ \ \
[3] [7] [20] ← level 2 (3 and 7 are leaves; 20 is a leaf)
Types of binary trees:
- Full binary tree: every node has 0 or 2 children
- Complete binary tree: all levels filled except possibly the last, which is filled left to right
- Perfect binary tree: all internal nodes have 2 children; all leaves at the same level
7.3 Binary Search Tree (BST) Operations
A BST maintains the property: left subtree values < node value < right subtree values at every node.
Search in BST (C):
struct Node* search(struct Node* root, int key) {
if (root == NULL || root->data == key) return root;
if (key < root->data)
return search(root->left, key); // go left
return search(root->right, key); // go right
}
Insert in BST:
struct Node* insert(struct Node* root, int key) {
if (root == NULL) {
struct Node* n = malloc(sizeof(struct Node));
n->data = key; n->left = n->right = NULL;
return n;
}
if (key < root->data)
root->left = insert(root->left, key);
else if (key > root->data)
root->right = insert(root->right, key);
return root;
}
7.4 Tree Traversals
Traversal visits every node exactly once. Order differs by when the root is visited relative to its subtrees.
| Traversal | Order | Use |
|---|---|---|
| Pre-order | Root → Left → Right | Copy a tree; expression prefix form |
| In-order | Left → Root → Right | BST in-order gives sorted sequence |
| Post-order | Left → Right → Root | Delete a tree; expression postfix form |
In-order traversal (C):
void inorder(struct Node* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
Example — traversals of the tree above (10, 5, 15, 3, 7, 20):
- Pre-order: 10 5 3 7 15 20
- In-order: 3 5 7 10 15 20 ← sorted!
- Post-order: 3 7 5 20 15 10
graph TD
A[10] --> B[5]
A --> C[15]
B --> D[3]
B --> E[7]
C --> F[20]
The tree above shows a valid BST. In-order traversal (left → root → right) always produces a sorted sequence from a BST.
7.5 Tree Height, Level, and Depth
For the tree above:
- Height of node 5 = 1 (longest path to leaf: 5→3 or 5→7)
- Height of tree = 2 (height of root 10)
- Depth of node 20 = 2
7.6 AVL Trees (Balanced Trees)
An AVL tree is a self-balancing BST. The balance factor of each node = height(left subtree) − height(right subtree), and must stay in {−1, 0, 1}.
When an insertion or deletion makes a balance factor 2 or −2, the tree performs a rotation to restore balance:
- LL rotation (left-left case): single right rotation
- RR rotation (right-right case): single left rotation
- LR rotation (left-right case): left rotation on child, then right rotation on root
- RL rotation (right-left case): right rotation on child, then left rotation on root
Why AVL matters: An unbalanced BST degenerates to O(n) search when insertions are sorted (the tree becomes a chain). AVL guarantees O(log n) search, insert, and delete.
7.7 Huffman Algorithm
The Huffman algorithm builds an optimal prefix-free binary code for data compression.
Steps:
- Count the frequency of each symbol.
- Create a leaf node for each symbol.
- Repeatedly take the two nodes with the lowest frequency, create a parent node with their combined frequency, and add it back.
- The resulting tree assigns shorter codes to more frequent symbols.
Example: Symbols A(5), B(3), C(2), D(1).
Step 1: nodes: A(5), B(3), C(2), D(1)
Step 2: merge D(1)+C(2) → CD(3)
Step 3: merge CD(3)+B(3) → BCD(6)
Step 4: merge A(5)+BCD(6) → root(11)
Codes: A=0, B=10, C=110, D=111 (shorter codes for more frequent symbols).
7.8 B-Tree
A B-tree of order m is a balanced search tree where:
- Every node has at most m children.
- Every non-root node has at least ⌈m/2⌉ children.
- All leaves are at the same level.
B-trees are used in databases and file systems because they minimize disk reads — each node stores many keys, so the tree is very short (height ≈ log_m(n)).
Key Terms — Unit 7
- BST property — left < node < right at every node
- In-order traversal — produces sorted output from a BST
- Balance factor — height(left) − height(right)
- AVL rotation — LL, RR, LR, RL
Unit 7 Practice Questions
Q1. Insert 50, 30, 70, 20, 40 into an empty BST and show the resulting tree. (50 is root; 30 goes left of 50; 70 goes right; 20 goes left of 30; 40 goes right of 30.)
Q2. Why does in-order traversal of a BST produce a sorted sequence? (Because BST property ensures all left subtree values are less than the node, and all right subtree values are greater; traversing left → node → right respects that order.)
Unit 8: Sorting
Teaching hours: 5
8.1 Introduction and Classification
Sorting arranges elements in a defined order (ascending or descending). It is one of the most studied problems in computer science because it underlies search, database query optimization, and many other algorithms.
| Category | Algorithms |
|---|---|
| Internal sort | All data fits in RAM |
| External sort | Data on disk, too large for RAM |
| Comparison-based | Bubble, insertion, selection, quick, merge, heap |
| Non-comparison | Radix sort, counting sort |
8.2 Insertion Sort
Idea: Build a sorted sub-array from left to right. For each new element, insert it into its correct position in the sorted portion by shifting larger elements right.
C code:
void insertionSort(int a[], int n) {
for (int i = 1; i < n; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j+1] = a[j]; // shift right
j--;
}
a[j+1] = key;
}
}
Trace — sort [5, 2, 4, 1]:
i=1: key=2, shift 5 right → [5,5,4,1], insert 2 → [2,5,4,1]
i=2: key=4, shift 5 right → [2,5,5,1], insert 4 → [2,4,5,1]
i=3: key=1, shift 5,4,2 right → [2,4,5,5] → [2,4,4,5] → [2,2,4,5], insert 1 → [1,2,4,5]
Complexity: O(n²) worst/average, O(n) best (already sorted). Good for small or nearly sorted arrays.
8.3 Selection Sort
Idea: Find the minimum element in the unsorted portion and swap it with the first unsorted position.
void selectionSort(int a[], int n) {
for (int i = 0; i < n-1; i++) {
int minIdx = i;
for (int j = i+1; j < n; j++)
if (a[j] < a[minIdx]) minIdx = j;
int tmp = a[i]; a[i] = a[minIdx]; a[minIdx] = tmp;
}
}
Complexity: Always O(n²). Makes exactly n−1 swaps — useful when writes are expensive.
8.4 Bubble Sort
Idea: Repeatedly compare adjacent elements and swap if out of order. Largest element "bubbles" to the end in each pass.
void bubbleSort(int a[], int n) {
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (a[j] > a[j+1]) {
int tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp;
}
}
Complexity: O(n²) worst/average, O(n) best with early-exit optimization.
8.5 Quick Sort
Idea: Select a pivot, partition the array so all elements less than pivot go left and all elements greater go right, then recursively sort each partition.
int partition(int a[], int low, int high) {
int pivot = a[high]; // choose last element as pivot
int i = low - 1;
for (int j = low; j < high; j++) {
if (a[j] <= pivot) {
i++;
int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
}
}
int tmp = a[i+1]; a[i+1] = a[high]; a[high] = tmp;
return i + 1;
}
void quickSort(int a[], int low, int high) {
if (low < high) {
int pi = partition(a, low, high);
quickSort(a, low, pi - 1);
quickSort(a, pi + 1, high);
}
}
Complexity: O(n log n) average, O(n²) worst (sorted input with bad pivot choice). Best practical sorting algorithm for average cases.
8.6 Merge Sort
Idea: Divide the array in half, recursively sort each half, then merge the two sorted halves.
void merge(int a[], int l, int m, int r) {
int n1 = m - l + 1, n2 = r - m;
int L[n1], R[n2];
for (int i=0; i<n1; i++) L[i] = a[l+i];
for (int j=0; j<n2; j++) R[j] = a[m+1+j];
int i=0, j=0, k=l;
while (i<n1 && j<n2)
a[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
while (i<n1) a[k++] = L[i++];
while (j<n2) a[k++] = R[j++];
}
void mergeSort(int a[], int l, int r) {
if (l < r) {
int m = (l + r) / 2;
mergeSort(a, l, m);
mergeSort(a, m+1, r);
merge(a, l, m, r);
}
}
Complexity: O(n log n) all cases. Requires O(n) extra memory. Preferred for linked lists and external sorting.
8.7 Heap Sort
Idea: Build a max-heap from the array, then repeatedly extract the maximum (swap root with last element, reduce heap size, re-heapify).
Complexity: O(n log n) guaranteed. In-place (no extra memory). Slower in practice than quick sort due to cache effects.
8.8 Shell Sort
Idea: Generalization of insertion sort. Sort elements that are h positions apart, gradually reducing h to 1 (final pass is ordinary insertion sort). Early large-h passes allow big jumps.
Complexity: Depends on gap sequence; O(n^1.5) with Knuth's sequence. Better than O(n²) for medium-sized arrays.
8.9 Radix Sort
Idea: Sort by individual digits from least significant to most significant (LSD radix sort), using a stable sort (like counting sort) at each digit level.
Example: Sort [170, 45, 75, 90, 802, 24, 2, 66]:
By ones digit: 170, 90, 802, 2, 24, 45, 75, 66
By tens digit: 802, 2, 24, 45, 66, 170, 75, 90
By hundreds: 2, 24, 45, 66, 75, 90, 170, 802
Sorted!
Complexity: O(d × n) where d = number of digits. Not comparison-based; can beat O(n log n) for specific inputs.
8.10 Efficiency Summary (Big-O Notation)
Big-O describes how time grows with input size n.
| Notation | Growth | Example |
|---|---|---|
| O(1) | Constant | Array index access |
| O(log n) | Logarithmic | Binary search |
| O(n) | Linear | Sequential scan |
| O(n log n) | Linearithmic | Merge sort, quick sort avg |
| O(n²) | Quadratic | Bubble, insertion, selection sort |
| O(2ⁿ) | Exponential | Naive Fibonacci |
Sorting algorithm comparison:
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Insertion | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection | O(n²) | O(n²) | O(n²) | O(1) | No |
| Bubble | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Quick | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Heap | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Shell | O(n log n) | O(n^1.5) | O(n²) | O(1) | No |
| Radix | O(nk) | O(nk) | O(nk) | O(n+k) | Yes |
Swipe to see all columns
Unit 9: Searching
Teaching hours: 5
9.1 Introduction
Searching locates a target value (key) within a collection. The right algorithm depends on whether data is sorted, the data structure used, and the expected frequency of searches.
9.2 Sequential (Linear) Search
Scan every element from the beginning until the key is found or the array is exhausted.
int linearSearch(int a[], int n, int key) {
for (int i = 0; i < n; i++)
if (a[i] == key) return i;
return -1; // not found
}
Complexity: O(n) — no precondition needed. Use when data is unsorted or very small.
9.3 Binary Search
Binary search requires a sorted array. It compares the key with the middle element:
- If equal, found.
- If key < middle, search left half.
- If key > middle, search right half.
int binarySearch(int a[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == key) return mid;
else if (a[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
Trace — search for 7 in [1, 3, 5, 7, 9, 11, 13]:
low=0, high=6, mid=3 → a[3]=7 == key → found at index 3
Complexity: O(log n). With n=1 000 000, binary search needs at most 20 comparisons; linear search needs up to 1 000 000.
9.4 Tree Search
Searching in a BST is O(log n) average for balanced trees (see Unit 7). In the worst case (degenerate/unbalanced tree), it degrades to O(n).
9.5 Hashing
Hashing maps a key to a fixed-size index (hash code) using a hash function, then stores the value at that index in a hash table.
Goal: O(1) average search, insert, and delete.
Common hash functions:
- Division:
h(k) = k % m(m is table size, choose m prime) - Multiplication:
h(k) = floor(m * (k * A mod 1))where A ≈ 0.618
Collision: Two keys map to the same index. Must be resolved.
Collision Resolution Techniques
1. Chaining (open hashing): Each table slot holds a linked list. Colliding entries are appended to the list.
Table index 3: → [15] → [29] → NULL
2. Open addressing (closed hashing): When a slot is occupied, probe for another slot.
- Linear probing:
h(k, i) = (h(k) + i) % m— check next slot - Quadratic probing:
h(k, i) = (h(k) + i²) % m - Double hashing:
h(k, i) = (h1(k) + i × h2(k)) % m
Load factor λ = n/m (entries/table size). Performance degrades as λ → 1.
Example — chaining with h(k) = k % 7, insert 10, 17, 3, 24:
10 % 7 = 3 → slot 3: [10]
17 % 7 = 3 → slot 3: [10] → [17]
3 % 7 = 3 → slot 3: [10] → [17] → [3]
24 % 7 = 3 → slot 3: [10] → [17] → [3] → [24]
(Bad hash — all keys go to same slot. Load balancing matters.)
9.6 Efficiency Comparison
| Method | Average | Worst | Requires |
|---|---|---|---|
| Linear search | O(n) | O(n) | Nothing |
| Binary search | O(log n) | O(log n) | Sorted array |
| BST search | O(log n) | O(n) | BST structure |
| Hash (chaining) | O(1) | O(n) | Hash function + extra memory |
Swipe to see all columns
Unit 10: Graphs
Teaching hours: 5
10.1 Introduction and ADT
A graph G = (V, E) consists of a set of vertices (V) and a set of edges (E). Graphs model relationships: social networks, road maps, computer networks.
Types of graphs:
| Type | Description |
|---|---|
| Undirected | Edges have no direction: {u, v} = {v, u} |
| Directed (Digraph) | Edges have direction: (u → v) ≠ (v → u) |
| Weighted | Edges have numeric weights (distances, costs) |
| Cyclic / Acyclic | Contains / does not contain a cycle |
| Connected | Path exists between every pair of vertices |
10.2 Graph Representations
Adjacency Matrix: 2D array adj[n][n]. adj[i][j] = 1 if edge exists.
- Space: O(V²)
- Fast to check if an edge exists: O(1)
- Wasteful for sparse graphs
Adjacency List: Array of linked lists. adj[i] lists neighbors of vertex i.
- Space: O(V + E)
- Efficient for sparse graphs
Graph: 0—1, 0—2, 1—3
Matrix: List:
0 1 2 3 0: [1, 2]
0 [0,1,1,0] 1: [0, 3]
1 [1,0,0,1] 2: [0]
2 [1,0,0,0] 3: [1]
3 [0,1,0,0]
10.3 Graph Traversal
Breadth-First Search (BFS)
Visits all neighbors of the current vertex before going deeper. Uses a queue.
BFS from 0 on graph above:
Queue: [0] Visited: {0}
Dequeue 0, enqueue 1,2 → Queue:[1,2] Visited:{0,1,2}
Dequeue 1, enqueue 3 → Queue:[2,3] Visited:{0,1,2,3}
Dequeue 2 (no new) → Queue:[3]
Dequeue 3 (no new) → Queue:[]
Order: 0, 1, 2, 3
BFS finds shortest path (by hop count) in unweighted graphs.
Depth-First Search (DFS)
Goes as deep as possible before backtracking. Uses a stack (or recursion).
DFS from 0: 0 → 1 → 3 (backtrack) → (backtrack) → 2
Applications: Topological sort, cycle detection, connected components.
10.4 Spanning Trees and Kruskal's Algorithm
A spanning tree of a connected graph is a subset of edges that connects all vertices with no cycle. A minimum spanning tree (MST) minimizes the total edge weight.
Kruskal's Algorithm:
- Sort all edges by weight.
- Add each edge to the MST if it does not create a cycle (use Union-Find to detect cycles).
graph LR
A -- 1 --- B
A -- 4 --- C
B -- 2 --- C
B -- 5 --- D
C -- 3 --- D
Sort edges: AB(1), BC(2), CD(3), AC(4), BD(5). Add AB, BC, CD — all connect new vertices. Skip AC (creates cycle A-B-C-A). MST = {AB, BC, CD}, total weight = 6.
10.5 Shortest Path — Dijkstra's Algorithm
Finds the shortest path from a source vertex to all other vertices in a weighted graph with non-negative weights.
Steps:
- Set distance to source = 0; all others = ∞.
- Mark all vertices unvisited.
- For the unvisited vertex with smallest distance, update distances of its neighbors.
- Mark it visited.
- Repeat until all vertices are visited.
Example: Graph with vertices {A, B, C, D}, edges A→B(1), A→C(4), B→C(2), B→D(5), C→D(1). Source = A.
Init: dist={A:0, B:∞, C:∞, D:∞}
Visit A: update B=1, C=4
Visit B (dist=1): update C=min(4,1+2)=3, D=min(∞,1+5)=6
Visit C (dist=3): update D=min(6,3+1)=4
Visit D (dist=4): done
Shortest distances from A: B=1, C=3, D=4
10.6 Warshall's Algorithm (Transitive Closure)
Floyd-Warshall finds the transitive closure of a graph: determines which vertices are reachable from which others.
For k from 0 to n-1:
For i from 0 to n-1:
For j from 0 to n-1:
reach[i][j] = reach[i][j] OR (reach[i][k] AND reach[k][j])
Complexity: O(V³).
10.7 Greedy Algorithm
The greedy approach makes the locally optimal choice at each step hoping to find a global optimum. Dijkstra's and Kruskal's are greedy algorithms.
Works when: A greedy choice property holds and optimal substructure exists.
Key Terms — Unit 10
- Vertex / Edge — node and connection in a graph
- BFS — uses queue; finds shortest path in unweighted graph
- DFS — uses stack/recursion; explores depth-first
- MST — minimum spanning tree
- Dijkstra — single-source shortest path, non-negative weights
- Greedy — locally optimal choice at each step
Unit 11: Algorithms
Teaching hours: 5
11.1 Deterministic vs. Non-deterministic Algorithms
| Type | Description | Example |
|---|---|---|
| Deterministic | Same input → same sequence of steps → same output | Binary search |
| Non-deterministic | May make random or parallel choices; multiple paths possible | NP problems, randomized algorithms |
Non-deterministic algorithms are theoretical models used to study complexity classes (P vs. NP). In practice, randomized algorithms (like randomized quick sort) introduce controlled randomness to improve average performance.
11.2 Divide and Conquer
Strategy: Break the problem into smaller subproblems of the same type, solve them recursively, and combine results.
divide_and_conquer(problem):
if problem is small enough:
solve directly
else:
sub1, sub2 = divide(problem)
sol1 = divide_and_conquer(sub1)
sol2 = divide_and_conquer(sub2)
return combine(sol1, sol2)
Examples: Merge sort, quick sort, binary search, Strassen's matrix multiplication.
Master Theorem: For T(n) = aT(n/b) + f(n):
- Compare f(n) with n^(log_b a)
- If f(n) = O(n^(log_b a − ε)): T(n) = Θ(n^(log_b a))
- If f(n) = Θ(n^(log_b a)): T(n) = Θ(n^(log_b a) × log n)
- If f(n) = Ω(n^(log_b a + ε)): T(n) = Θ(f(n))
Merge sort analysis: T(n) = 2T(n/2) + n → a=2, b=2, f(n)=n, log_2(2)=1 → f(n) = n = Θ(n¹) → T(n) = Θ(n log n).
11.3 Series and Parallel Algorithms
| Type | Description |
|---|---|
| Series (sequential) | Steps execute one after another |
| Parallel | Multiple steps execute simultaneously on different processors |
Parallel algorithms exploit multi-core processors to reduce wall-clock time. Example: parallel merge sort splits the array and sorts each half simultaneously on separate cores.
Speedup: S = T_serial / T_parallel. Amdahl's Law limits speedup if any sequential portion exists.
11.4 Heuristic and Approximate Algorithms
For NP-hard problems (problems where no polynomial-time algorithm is known), exact algorithms are too slow for large inputs. Two practical alternatives:
Heuristic algorithms: Use rules of thumb to find a good (not necessarily optimal) solution quickly. No guarantee of optimality. Example: nearest-neighbor heuristic for the Travelling Salesman Problem.
Approximate algorithms: Provide a provable bound on how far from optimal the solution is. Example: a 2-approximation for vertex cover guarantees the solution is at most 2× the optimal size.
When to use each:
- Exact: small input, optimality required
- Heuristic: large input, good-enough solution acceptable
- Approximate: large input, bounded error required
Key Terms — Unit 11
- Divide and conquer — split, solve recursively, combine
- Deterministic — reproducible output for same input
- Heuristic — fast rule-of-thumb, no optimality guarantee
- Approximate — provable error bound, not necessarily optimal
- Parallel algorithm — simultaneous execution on multiple processors
Course-Level Key Terms
| Term | Definition |
|---|---|
| ADT | Abstract Data Type — specification without implementation |
| Big-O | Asymptotic upper bound on algorithm growth rate |
| LIFO | Last In, First Out (stack) |
| FIFO | First In, First Out (queue) |
| BST | Binary Search Tree |
| AVL | Self-balancing BST with balance-factor constraint |
| MST | Minimum Spanning Tree |
| BFS | Breadth-First Search |
| DFS | Depth-First Search |
| Hash table | Array indexed by hash function output |
| Collision | Two keys mapping to the same hash slot |
| Traversal | Visiting every node in a tree or graph exactly once |
Detailed Practice Questions and Answer Key
Q1. Write the algorithm for inserting a node at the beginning of a singly linked list and state its time complexity.
Answer: Create a new node. Set new node's next to current head. Update head to point to new node. Time complexity: O(1) — no traversal needed regardless of list length.
Q2. Convert the infix expression (A + B) * C - D / E to postfix using a stack. Show the full trace.
Answer:
Token Stack Output
( [(]
A [(] A
+ [(, +] A
B [(, +] A B
) [] A B + (pop until (, discard ()
* [*] A B +
C [*] A B + C
- [-] A B + C * (pop * before push -)
D [-, /] A B + C * D (wait, push /)
Actually: - is on stack, then / has higher prec, push
/ [-, /] A B + C * D
E [-, /] A B + C * D E
end [] A B + C * D E / -
Result: A B + C * D E / -
Q3. Explain the difference between BFS and DFS for graph traversal. When would you choose each?
Answer: BFS uses a queue and explores level by level — all neighbors before going deeper. DFS uses a stack/recursion and goes as deep as possible before backtracking. Choose BFS for shortest path in unweighted graphs and to find all vertices at the same distance from the source. Choose DFS for cycle detection, topological sorting, and finding connected components.
Q4. Given the array [64, 34, 25, 12, 22, 11, 90], trace the selection sort algorithm showing each pass.
Answer:
Pass 1: min=11 at index 5; swap with index 0 → [11, 34, 25, 12, 22, 64, 90]
Pass 2: min=12 at index 3; swap with index 1 → [11, 12, 25, 34, 22, 64, 90]
Pass 3: min=22 at index 4; swap with index 2 → [11, 12, 22, 34, 25, 64, 90]
Pass 4: min=25 at index 4; swap with index 3 → [11, 12, 22, 25, 34, 64, 90]
Pass 5: min=34 at index 4; already in place → [11, 12, 22, 25, 34, 64, 90]
Pass 6: min=64 at index 5; already in place → [11, 12, 22, 25, 34, 64, 90]
Sorted: [11, 12, 22, 25, 34, 64, 90]
Q5. What is a hash collision? Describe two methods to handle it.
Answer: A collision occurs when two different keys produce the same hash index.
Chaining: Each table slot contains a linked list. All keys that hash to the same slot are stored in the list. Search requires traversing the list at that slot. Worst case: all keys in one slot, O(n) search.
Linear probing (open addressing): When a collision occurs at index h, probe h+1, h+2, ... until an empty slot is found (wrapping around). Can cause clustering — consecutive occupied slots slow subsequent insertions.
Q6. An AVL tree currently has a balance factor of 2 at some node. What does that indicate and what must be done?
Answer: A balance factor of 2 means the left subtree is 2 levels taller than the right subtree. The tree is unbalanced at that node. A rotation must be performed. If the left child's balance factor is positive (left-heavy), perform a single right rotation (LL case). If the left child's balance factor is negative (right-heavy), perform a left rotation on the left child followed by a right rotation on the current node (LR case).
References
- Tribhuvan University BCA 2025 syllabus — BCA201, Data Structure and Algorithm
Source:content/syllabi/semester-3/data-structure-and-algorithm/2025.md
SHA-256:sha256:02eee32d756f2decf7604fad66b99d508744e055f14d4e480fc2a92327b8062a
Note: the official 2025 source lists the course but contains no detailed numbered unit outline (verification: partial,status: staged). The 11-unit structure in this guide is adapted from the earlier CACS201 outline pending verification against a 2025 unit outline.