Ticker

6/recent/ticker-posts

Ticker

6/recent/ticker-posts

Ad Code

A6-R4: DATA STRUCTURE THROUGH C++

 A6-R4: DATA STRUCTURE THROUGH C++ ( July 2010)


NOTE:

1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions 
and PART TWO contains FIVE questions. 

2. PART ONE is to be answered in the TEAR-OFF ANSWER SHEET only, attached to the 
question paper, as per the instructions contained therein. PART ONE is NOT to be 
answered in the answer book. 

3. Maximum time allotted for PART ONE is ONE HOUR. Answer book for PART TWO will 
be supplied at the table when the answer sheet for PART ONE is returned. 
However, candidates, who complete PART ONE earlier than one hour, can collect the answer book for PART TWO immediately after handing over the answer sheet for PART ONE.
 
TOTAL TIME: 3 HOURS TOTAL MARKS: 100  (PART ONE – 40; PART TWO – 60) 

PART ONE 

(Answer all the questions) 

1. Each question below gives a multiple choice of answers. Choose the most 
appropriate one and enter in the “tear-off” answer sheet attached to the question 
paper, following instructions therein.


1.1 Given two sorted list of size ‘m’ and ‘n’ respectively. The number of comparisons needed in the worst case by the merge sort algorithm will be 

A) m*n 
B) maximum of m, n
C) minimum of m, n 
D) m + n –1 


1.  First understand: What is a sorted list?

A sorted list means elements are arranged in ascending or descending order.

Example:

* List 1: `[10, 20, 30]`

* List 2: `[15, 25, 35]`

Both lists are already sorted.

Our task is to merge them into one sorted list.

2. How does the merge algorithm work?

We compare the first elements of both lists.

Let's see the actual merging process for our two lists.

| Comparison | Result        |
| ---------- | ------------- |
| 10 vs 15   | 10 is smaller |
| 20 vs 15   | 15 is smaller |
| 20 vs 25   | 20 is smaller |
| 30 vs 25   | 25 is smaller |
| 30 vs 35   | 30 is smaller |

Now only 35 remains, so we add it directly without comparison.

Final sorted list:

`10, 15, 20, 25, 30, 35`

Total comparisons = 5

Here:

* m = 3

* n = 3

* Comparisons = 3 + 3 – 1 = 5


 3. Important formula for exam

Maximum comparisons=m+n-1

*Why minus 1

Because when one list becomes empty, the remaining elements of the other list are copied directly. No further comparisons are needed.

Remember:

* Best case: comparisons. = Min (m,n)

* Worst case: comparisons. M+n - 1


1.2 The postfix equivalent of the prefix * + ab – cd is 

A) ab + cd – * 
B) abcd + – * 
C) ab + cd* – 
D) ab + – cd* 

1. First understand expressions

There are three common types of expressions in Data Structures.

| Expression | Meaning                   | Example |
| ---------- | ------------------------- | ------- |
| Infix      | Operator between operands | A + B   |
| Prefix     | Operator before operands  | + AB    |
| Postfix    | Operator after operands   | AB +    |

Understand these three:

Infix

A + B

Operator is in the middle.

Prefix

+ A B

Operator comes first.

Postfix

 A B +

Operator comes last.

2. Understand the given expression

Given prefix:

`* + a b - c d`

Let's break it into parts.

* `+ a b` means a + b

* `- c d` means c - d

* `*` means multiplication of both results.

So the expression is:

(a+b) times (c-d)

Now convert each part into postfix.

Step 1: Convert `+ a b`

Postfix = `ab+`

Step 2: Convert `- c d`

Postfix = `cd-`

Step 3: Apply multiplication at the end.

Combine both expressions and put `*` at the end:

`ab+ cd- *`

Final Answer: A

 3. Shortcut to remember

| Prefix | Postfix |
| ------ | ------- |
| + AB   | AB+     |
| - AB   | AB-     |
| * AB   | AB*     |
| / AB   | AB/     |


1.3 Which of the following statements are true in case of Depth-First-Traversal? 

i) DFS is used to determine connected components of an undirected graph. 
ii) DFS is used to determine acyclic nature of a graph. 

A) only i) is true 
B) only ii) is true 
C) both i) & ii) are true 
D) both i) & ii) are false 

Correct Answer: C) Both i) & ii) are true

Let's understand this question from the basics

1 What is DFS (Depth-First Search)?

DFS stands for Depth-First Search.

It is a graph traversal algorithm used to visit all vertices (nodes) of a graph.

Its basic rule is:

Go as deep as possible in one direction, then come back (Backtracking).

Example:

Example of DFS traversal

### A → B → D → E → C → F → G

One possible DFS order, depending on the order in which neighbours are visited.

DFS uses:

* Stack (LIFO)

* Recursion (commonly used)

2. Understand statement i)

DFS is used to determine connected components of an undirected graph.

What are connected components?

A connected component is a group of vertices in which every vertex can be reached from every other vertex in that group.


Suppose a graph has three separate groups:

* Group 1: A, B, C

* Group 2: D, E

* Group 3: F, G

DFS can visit each group separately and identify all three connected components.

Statement i is TRUE





 3\. Understand statement ii)

DFS is used to determine the acyclic nature of a graph.

First, understand two words:

* Cyclic graph = A graph containing a cycle (a closed path).

* Acyclic graph = A graph containing no cycle.


1.4 Structure in C++ is a/an 

A) user defined data type 
B) ADT 
C) both A) and B) 
D) none of the above 

Correct Answer: C) Both A and B

Explanation:

In C++, a structure is a user-defined data type because the programmer creates it using the `struct` keyword.

It is also considered an Abstract Data Type (ADT) because it can group different types of data and related functions together.

Example:

```c++

struct Student {
    int rollNo;
    string name;
};
```

Here, `Student` is a structure that stores different types of data in one unit.

Remember: Structure in C++ is a user-defined data type and can be used to implement an ADT.,



1.5 What is the balancing condition of an AVL tree?

A) Height factor between +2 and –2 
B) Height factor between +1 and –1 
C) Height factor between 0 and –1 
D) None of the above

Correct Answer: B) Height factor between +1 and –1
Explanation:
An AVL tree is a self-balancing Binary Search Tree (BST). In an AVL tree, the height difference between the left and right subtrees of every node should be -1, 0, or +1.
This difference is called the Balance Factor (BF).
Formula:
BF = Height(Left) - Height(Right)
Remember for exams:
* BF = 0 → Balanced
* BF = +1 → Balanced
* BF = -1 → Balanced
* BF = +2 or -2 → Unbalanced (rotation required)
Answer: Option B.


1.6 The initial configuration of a queue is a b c d , , , (a is in the front of queue). To get the configuration d c b a , , , one needs minimum of 

A) 2 deletions and 3 additions 
B) 3 deletions and 2 additions 
C) 3 deletions and 3 additions 
D) 3 deletions and 4 additions 

Correct Answer: C) 3 deletions and 3 additions.
Explanation:
Initial queue: `a, b, c, d`
To get the reverse order `d, c, b, a`:
* First, delete `a`, `b` and `c` (3 deletions).
* Then, add the required elements back in reverse order using the queue operations (3 additions).
Remember: Queue follows FIFO (First In, First Out).


1.7 A full binary tree with n leaves contains 

A) n nodes 
B) 2 log n nodes 
C) 2 n − 1 nodes 
D) 2n nodes 

Correct Answer: C) 2n − 1 nodes

Explanation:

A full binary tree is a tree in which every node has either:

* 0 children (leaf node), or

* 2 children.

The formula for the total number of nodes is:

\\text{Total Nodes} = 2n - 1

Here, `n` is the number of leaf nodes.

Example:

If a full binary tree has 4 leaf nodes:

2(4)-1 = 8-1 = 7

So, the total number of nodes will be 7.

Remember: Full Binary Tree = 2n − 1 nodes.


1.8 In linked list, the logical order of elements 

A) is same as their physical arrangement 
B) is not necessarily equivalent to their physical arrangement 
C) is determined by their physical arrangement 
D) none of the above 

Correct Answer: B) is not necessarily equivalent to their physical arrangement.

Explanation:

In a linked list, elements are connected through pointers (links). They do not need to be stored next to each other in memory.

For example:

Logical order: `10 → 20 → 30 → 40`

But their actual memory locations can be different, such as:

* 10 stored at address 100

* 20 stored at address 500

* 30 stored at address 200

* 40 stored at address 800

Pointers connect them in the correct order.

Remember: In an array, elements are stored in continuous memory locations, but in a link ofed list, they can be stored anywhere in memory.

Answer: Option B.



1.9 A is an array of size m n ∗ , stored in the row major order. If the address of the first 
element in the array is M, the address of the element A( i, j ) ( A ( , 0,0 )) is the first 
element of the array and each element occupies one unit of memory location in memory 

A) M+(i-j)* m+j-1

B)M+i*m+j

C)M+(j-1) * m+i-1

 D) M+(i-1)* n+j-1

Correct Answer: D) M + (i − 1) × n + j − 1

### Explanation in simple words

The question is asking how to find the memory address of an element in a 2D array.

First, understand Row Major Order.

Row Major means elements are stored row by row.

For example, a 3 × 3 array:

```text
  1    2    3
  4    5    6
  7    8    9
```

In memory, they are stored like this:

`1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9`

### Formula

Address = M+(i-1)\\times n+(j-1)

Here:

* M = Starting memory address

* i = Row number

* j = Column number

* n = Total number of columns

### Example

Suppose:

* M = 100

* n = 3

* i = 2

* j = 2

Put the values in the formula:

=100+(2-1)\\times3+(2-1)=100+3+1=104

So, the address is 104.

### Easy trick to remember for MCQs

* Row Major → Multiply by columns (n).

* Column Major → Multiply by rows (m).

Final Answer: Option D.


1.10 Which is not representation of a graph? 

A) Adjacency matrix 
B) Edge list 
C) Adjacency list 
D) None of the above

Correct Answer: D) None of the above

Explanation:

All three are valid representations of a graph in Data Structures.

* Adjacency Matrix: A 2D array that represents connections between vertices (nodes).

* Edge List: Stores all edges as pairs of vertices.

* Adjacency List: Stores each vertex along with its adjacent vertices.

Exam Trick: Remember these three graph representations:

* Adjacency Matrix

* Adjacency List

* Edge List

All three are valid. Therefore, the answer is D) None of the above.

___________________________________________________


2. Each statement below is either TRUE or FALSE. Choose the most appropriate one 
and ENTER in the “tear-off” sheet attached to the question paper, following 
instructions therein. (1x10) 

2.1 The maximum number of nodes in binary tree of depth 5 is 31. 

2.2 Worst case time complexity of the heap sort algorithm is O(n2). 

2.3 Complexity expressed in O-notation is upper bound. 

2.4 The first node of a linked list is pointed by a generic pointer. 

2.5 Queue is useful in implementing heap sort. 

2.6 A linear list that allows elements to be added or removed at either end but not in the 
middle is called stack. 

2.7 Linked lists are not suitable data structures for radix sort.

2.8 The adjacency matrix of an undirected graph is a unit matrix. 

2.9 BFS scans adjacent unvisited vertex as soon as possible. 

2.10 A simple undirected graph with eight (8) vertices is said to be complete if number of 
edges equals to 54.

2.1 TRUE
Maximum nodes = 2^d − 1 = 2^5 − 1 = 31.

Let's understand Question 2.1 step by step.

Statement: The maximum number of nodes in a binary tree of depth 5 is 31.

Answer: TRUE (assuming depth means 5 levels).

Step 1: Understand the formula

Maximum nodes in a binary tree:

N=2^d-1

Where:

* = Maximum number of nodes

* = Depth (number of levels)

 Step 2: Put depth = 5

N=2^5-1=32-1=31

 Step 3: Understand with a diagram

Binary Tree – 5 Levels

| Level | Maximum nodes |
| ----- | ------------- |
| 1     | 1             |
| 2     | 2             |
| 3     | 4             |
| 4     | 8             |
| 5     | 16            |
| Total | 31            |

Easy trick for exams:

Each level doubles the nodes:

1 + 2 + 4 + 8 + 16 = 31

Remember: A binary tree can have at most 2 children per node.



2.2 FALSE
Heap Sort worst-case time complexity is O(n log n), not O(n²).
Statement: Worst-case time complexity of Heap Sort algorithm is .
# Time Complexity and Algorithms – Notes

## 1. What is an Algorithm?

An algorithm is a step-by-step procedure used to solve a particular problem.

**Examples:**
- Searching algorithms
- Sorting algorithms
- Tree traversal algorithms
- Graph traversal algorithms

## 2. What is Time Complexity?

Time complexity tells us how the running time of an algorithm grows when the input size increases.

For example:
- 10 elements require less processing.
- 1,000 elements may require more processing.

Time complexity helps us measure the efficiency of an algorithm.

## 3. What is Worst-Case Time Complexity?

Worst-case time complexity means the maximum amount of time an algorithm can take for an input of a particular size.

**Example: Linear Search**

Array: 10, 20, 30, 40, 50

Suppose we want to search for 50.

The algorithm checks:
1. 10
2. 20
3. 30
4. 40
5. 50

Total comparisons = 5.

Therefore, worst-case time complexity is O(n).

## 4. Types of Time Complexity

| Complexity | Name | Example |
|---|---|---|
| O(1) | Constant | Array access |
| O(log n) | Logarithmic | Binary Search |
| O(n) | Linear | Linear Search |
| O(n log n) | Linearithmic | Merge Sort, Heap Sort |
| O(n²) | Quadratic | Bubble Sort |
| O(2ⁿ) | Exponential | Recursive Fibonacci |

## 5. Types of Cases

**1. Best Case:** Minimum time taken by an algorithm.

**2. Average Case:** Expected time taken over possible inputs.

**3. Worst Case:** Maximum time taken by an algorithm for a given input size.

Example: Linear Search

Array: 10, 20, 30, 40, 50

- Best Case: Search 10 → 1 comparison.
- Average Case: Search 30 → 3 comparisons.
- Worst Case: Search 50 → 5 comparisons.

## 6. Worst-Case Time Complexity of Sorting Algorithms

| Sorting Algorithm | Worst-Case Complexity |
|---|---|
| Bubble Sort | O(n²) |
| Selection Sort | O(n²) |
| Insertion Sort | O(n²) |
| Merge Sort | O(n log n) |
| Heap Sort | O(n log n) |
| Quick Sort | O(n²) |

## 7. Important Exam Points

1. Heap Sort = O(n log n).
2. Merge Sort = O(n log n).
3. Quick Sort = O(n²) in the worst case.
4. Linear Search = O(n).
5. Binary Search = O(log n).
6. Big-O notation represents an asymptotic upper bound.

**Remember:**
- Best Case = Minimum time.
- Average Case = Expected time.
- Worst Case = Maximum time.


2.3 TRUE
Big-O notation represents an asymptotic upper bound.

Big-O tells us the upper bound of an algorithm's growth rate.



2.4 FALSE
The first node is pointed to by the HEAD pointer, not necessarily a generic pointer.


2.5 FALSE
Heap Sort uses a heap data structure, not a queue.

2.6 FALSE
This is called a Deque (Double-Ended Queue), not a stack.

2.7 False
Linked lists can be used to implement Radix Sort.

2.8 FALSE
An undirected graph has a symmetric adjacency matrix, not necessarily a unit matrix.

2.9 TRUE
BFS visits adjacent unvisited vertices level by level using a queue.

2.10 FALSE
Maximum edges = n(n−1)/2 = 8×7/2 = 28, not 54.



3. Match words and phrases in column X with the closest related meaning/ word(s)/phrase(s) in column Y. Enter your selection in the “tear-off” answer sheet attached to the question paper, following instructions therein. (1x10) 

 X Y 

3.1 D-queue A. Height balanced tree 
3.2 Time Complexity B. Graph 
3.3 Inheritance C. Bubble sort 
3.4 Minimal Spanning Tree D. Stack 
3.5 Best case complexity of insertion sort E. Double ended queue 
3.6 Column major order representation F. Preorder traversal of a tree 
3.7 Mostly zero entries G. Recursion 
3.8 Adjacency list H. Hashing 
3.9 Merge Sort I. Worst time is O(n log n) 
3.10 DFS J. Big-Oh notation 
K. Building new class from an existing 
classes 
 L. O(n) 
 M. O(n2) 
 N. Array 
 O. Stack 
 P. Hashing 
 Q. Prim’s algorithm 
 R. Sparse Matrix

Answer:

Understand the concepts

3.1 D-queue → E. Double Ended Queue

Deque allows insertion and deletion from both ends (front and rear).


3.2 Time Complexity → J. Big-Oh notation

Big-O notation describes the asymptotic upper bound of an algorithm's growth.

3.3 Inheritance → K. Building new class from existing classes

Inheritance allows a new class to acquire properties and methods of an existing class.

3.4 Minimum Spanning Tree → Q. Prim's algorithm

Prim's algorithm finds a Minimum Spanning Tree (MST) of a connected, weighted, undirected graph.

3.5 Best case of Insertion Sort → L. O(n)

When elements are already sorted, Insertion Sort takes linear time.

3.6 Column Major Order → N. Array

Column-major order stores array elements column by column.

3.7 Mostly zero entries → R. Sparse Matrix

A matrix containing mostly zero values is called a Sparse Matrix.

3.8 Adjacency List → B. Graph

An adjacency list represents the connections between vertices of a graph.

3.9 Merge Sort → I. Worst time is O(n log n)

Merge Sort has O(n log n) worst-case time complexity.

3.10 DFS → D. Stack

Depth First Search uses a stack (or recursion).

### Quick revision trick

* Deque = Both ends

* Big-O = Upper bound

* Inheritance = Existing class

* MST = Prim's algorithm

* Insertion Sort best = O(n)

* Sparse Matrix = Mostly zeros

* Merge Sort = O(n log n)

* DFS = Stack

* BFS = Queue

Exam tip: Options F, G, H, M, O and P are distractors or unused options here.

4. Each statement below has a blank space to fit one of the word(s) or phrase(s) in 
the list below. Enter your choice in the “tear-off” answer sheet attached to the 
question paper, following instructions therein. (1x10) 
A. queue B. stack C. priority queue 
D. linked list E. polynomial F. generic pointer 
G. constant pointer H. void pointer I. graph 
J. time complexity K. space complexity L. open addressing 
M. hashing N. tree O. binary search tree 
P. B tree Q. AVL tree R. O(n2
) 
S. O(nlogn) T. O(n) U. Kruskal’s Algorithm 
V. Dijkstra’s Algorithm W. bfs X. dfs 


4.1 The ________ of an algorithm is the amount of time the computer requires to execute 
the algorithm. 
4.2 Best case complexity of bubble sort is ________. 
4.3 ________ is called a FIFO data structure. 
4.4 ________ is a data structure where data can be represented as a chain of nodes. 
4.5 Recursive functions are internally evaluated by using ________. 
4.6 The declaration int const *p = &a signifies p as a ________. 
4.7 ________ is a mathematical tool used to represent a physical problem. 
4.8 ________ is also known as the balanced order-n multiway search tree. 
4.9 ________ is an algorithm in graph theory that finds the shortest path. 
4.10 ________ is a general collision resolution scheme for a hash table

Correct Answers – 4.1 to 4.10

| Question | Correct answer       | Option |
| -------- | -------------------- | ------ |
| 4.1      | Time complexity      | J      |
| 4.2      | O(n)                 | T      |
| 4.3      | Queue                | A      |
| 4.4      | Linked list          | D      |
| 4.5      | Stack                | B      |
| 4.6      | Constant pointer*    | G      |
| 4.7      | Graph                | I      |
| 4.8      | B tree               | P      |
| 4.9      | Dijkstra's Algorithm | V      |
| 4.10     | Open addressing      | L      |

Important explanations for exams

4.2 Best-case Bubble Sort = O(n)

When the array is already sorted, an optimized Bubble Sort checks all elements once and performs no swaps.

4.3 Queue = FIFO

FIFO means First In, First Out.

4.5 Stack

Recursive functions use a stack to store function calls and return addresses.

4.6 Constant pointer

`int const *p = &a;` actually means pointer to a constant integer. You cannot modify the value through `p`, but you can change where `p` points. So the given option G is technically worded incorrectly.

4.9 Dijkstra's Algorithm

It finds shortest paths from a source vertex to other vertices in a graph with non-negative edge weights.

4.10 Open Addressing

It resolves collisions in a hash table by finding another available position within the table.

### Quick revision trick

* FIFO → Queue

* Recursion → Stack

* Chain of nodes → Linked List

* Shortest path → Dijkstra

* Balanced multiway tree → B Tree

* Collision resolution → Open Addressing

* Algorithm execution time → Time Complexity


5 (a) Create a class ‘shape’ and derive the classes, box, cube, cylinder from it. The class 
‘shape’ has functions volume() and whole-surface-area(). Override these two functions in 
each of these derived classes. The dimensions of the shapes (box, cube, cylinder) are to 
be taken from user. Write a main function to test the classes. 

b) Show that the function f (n) defined by 
 f (1) = 1 
 f (n) = f(n-1) + 1/n for n > 1 
 has the complexity O(log n). 


#include <iostream>
using namespace std;

// Base Class
class shape {
public:
    virtual double volume() = 0;
    virtual double whole_surface_area() = 0;
};

// Derived Class: Box
class box : public shape {
    double l, b, h;

public:
    box(double x, double y, double z) {
        l = x;
        b = y;
        h = z;
    }

    double volume() {
        return l * b * h;
    }

    double whole_surface_area() {
        return 2 * (l*b + b*h + h*l);
    }
};

// Derived Class: Cube
class cube : public shape {
    double s;

public:
    cube(double x) {
        s = x;
    }

    double volume() {
        return s * s * s;
    }

    double whole_surface_area() {
        return 6 * s * s;
    }
};

// Derived Class: Cylinder
class cylinder : public shape {
    double r, h;

public:
    cylinder(double x, double y) {
        r = x;
        h = y;
    }

    double volume() {
        return 3.14 * r * r * h;
    }

    double whole_surface_area() {
        return 2 * 3.14 * r * (r + h);
    }
};

// Main Function
int main() {
    double l, b, h, s, r, ch;

    cout << "Enter length, breadth and height: ";
    cin >> l >> b >> h;
    box B(l, b, h);

    cout << "Box Volume: " << B.volume() << endl;
    cout << "Box Surface Area: "
         << B.whole_surface_area() << endl;

    cout << "Enter cube side: ";
    cin >> s;
    cube C(s);

    cout << "Cube Volume: " << C.volume() << endl;
    cout << "Cube Surface Area: "
         << C.whole_surface_area() << endl;

    cout << "Enter cylinder radius and height: ";
    cin >> r >> ch;
    cylinder CY(r, ch);

    cout << "Cylinder Volume: " << CY.volume() << endl;
    cout << "Cylinder Surface Area: "
         << CY.whole_surface_area() << endl;

    return 0;
}


(B). 

Q.5 (b) Show that the function f(n) has complexity O(log n). (6 Marks)

Given:

f(1) = 1

f(n) = f(n-1) + 1/n, for n > 1

Solution:

Step 1: Expand the recurrence relation.

For n = 2,

f(2) = f(1) + 1/2

= 1 + 1/2

For n = 3,

f(3) = f(2) + 1/3

= 1 + 1/2 + 1/3

Similarly,

f(n) = 1 + 1/2 + 1/3 + ... + 1/n

Step 2: Apply Harmonic Series Property.

We know that,

1 + 1/2 + 1/3 + ... + 1/n ≤ 1 + ln n

Therefore,

f(n) ≤ 1 + ln n

Step 3: Determine the Complexity.

Ignoring constant terms,

f(n) = O(log n)

Conclusion:

The given function represents a harmonic series, whose growth rate is logarithmic. Therefore, the complexity of the given function is O(log n).

Hence Proved.

6 Consider an array of size 25 × 4. Base address of this array is 200 and the word size 

is 4 units. The array is stored in row major form. Find the address of location A (12,3). 

Also find the address of the same element assuming that the array is stored in column 

major order. 

b) Consider the following infix expression: 

 A + B * (C + D) / F + D * E 

Convert the above expression in postfix form using stack. 

c) Write an algorithm to delete the last element from a single linked list. 

(6+6+3)

Answer - 

Q.6 (a) Find the address of A(12,3) in Row Major and Column Major order. (6 Marks)

Given:

Number of rows (M) = 25
Number of columns (N) = 4
Base Address (BA) = 200
Word Size (W) = 4 units
Location = A(12,3)

1. Row Major Order

Formula:

LOC(A[i,j]) = BA + W × (i × N + j)

Substituting the values:

= 200 + 4 × (12 × 4 + 3)

= 200 + 4 × (48 + 3)

= 200 + 4 × 51

= 200 + 204

Address = 404

2. Column Major Order

Formula:

LOC(A[i,j]) = BA + W × (j × M + i)

Substituting the values:

= 200 + 4 × (3 × 25 + 12)

= 200 + 4 × (75 + 12)

= 200 + 4 × 87

= 200 + 348

Address = 548

Final Answer:

Row Major Address = 404
Column Major Address = 548


Q.6 (b) Convert the following infix expression into postfix form using stack. (6 Marks)

Given Infix Expression:

A + B * (C + D) / F + D * E

Operator Precedence:

  1. Brackets ( )
  2. Multiplication (*) and Division (/)
  3. Addition (+)

Conversion Table:

Symbol Stack Postfix
A Empty A
+ + A
B + AB
* + * AB
( + * ( AB
C + * ( ABC
+ + * ( + ABC
D + * ( + ABCD
) + * ABCD+
/ + / ABCD+*
F + / ABCD+*F
+ + ABCD+*F/+
D + ABCD+*F/+D
* + * ABCD+*F/+D
E + * ABCD+*F/+DE
End Empty ABCD+F/+DE+

Final Postfix Expression:

ABCD+F/+DE+


Q.6 (c) Write an algorithm to delete the last element from a singly linked list. (3 Marks)

Algorithm: DELETE_LAST(START)

  1. Start.
  2. If START = NULL, then print "List is Empty" and return.
  3. If START->NEXT = NULL, then:
    • Free START.
    • Set START = NULL.
    • Return.
  4. Set PTR = START.
  5. Repeat while PTR->NEXT->NEXT != NULL:
    • PTR = PTR->NEXT.
  6. Set TEMP = PTR->NEXT.
  7. Set PTR->NEXT = NULL.
  8. Free TEMP.
  9. Stop.

Explanation:

  1. START points to the first node of the linked list.
  2. PTR is used to traverse the linked list.
  3. TEMP stores the address of the last node.
  4. The last node is deleted and the second-last node is made the last node.

Conclusion: The above algorithm deletes the last node from a singly linked list.


7. The following keys are to be inserted in the order shown below into an AVL Tree: 
25,45,50,55,60,65,75,85. Show how the tree appears after each insertion. 

b) The following keys are to be inserted in the order shown below into an B-tree 
(of order 5): a, g, f, b, k, d, h, m, j, e, s, i, r, x. Show how the tree appears after each 
insertion.  (8+7)

Ans 7. 

Q.7 (a) Insert the following keys into an AVL Tree and show the tree after each insertion. (8 Marks)

Given Keys:

25, 45, 50, 55, 60, 65, 75, 85

Solution:

An AVL Tree is a self-balancing Binary Search Tree (BST). The balance factor of every node must be -1, 0 or +1.

1. Insert 25

25

2. Insert 45

25
  \
   45

3. Insert 50

RR Rotation at 25.

    45
   /  \
 25    50

4. Insert 55

    45
   /  \
 25    50
         \
          55

5. Insert 60

RR Rotation at 50.

    45
   /  \
 25    55
      /  \
     50   60

6. Insert 65

RR Rotation at 45.

       55
      /  \
    45    60
   / \      \
 25  50      65

7. Insert 75

RR Rotation at 60.

       55
      /  \
    45    65
   / \   /  \
 25  50 60   75

8. Insert 85

       55
      /  \
    45    65
   / \   /  \
 25  50 60   75
                 \
                  85

Final AVL Tree:

       55
      /  \
    45    65
   / \   /  \
 25  50 60   75
                 \
                  85

Conclusion: AVL Tree maintains balance by performing rotations whenever necessary after insertion.


Q.7 (b) Insert the following keys into a B-Tree of order 5 and show the tree after each insertion. (7 Marks)

Given Keys:

a, g, f, b, k, d, h, m, j, e, s, i, r, x

Solution:

A B-Tree of order 5 has:

  1. Maximum 5 children.
  2. Maximum 4 keys in each node.
  3. When a node contains 5 keys, the middle key is promoted to the parent.

1. Insert a

[a]

2. Insert g

[a | g]

3. Insert f

[a | f | g]

4. Insert b

[a | b | f | g]

5. Insert k

          [f]
         /   \
     [a | b] [g | k]

6. Insert d

          [f]
         /   \
 [a | b | d] [g | k]

7. Insert h

          [f]
         /   \
 [a | b | d] [g | h | k]

8. Insert m

          [f]
         /   \
 [a | b | d] [g | h | k | m]

9. Insert j

             [f | j]
           /    |    \
 [a | b | d] [g | h] [k | m]

10. Insert e

             [f | j]
           /    |    \
[a | b | d | e] [g | h] [k | m]

11. Insert s

             [f | j]
           /    |    \
[a | b | d | e] [g | h] [k | m | s]

12. Insert i

              [f | j]
            /    |     \
[a | b | d | e] [g | h | i] [k | m | s]

13. Insert r

              [f | j]
            /    |     \
[a | b | d | e] [g | h | i] [k | m | r | s]

14. Insert x

After inserting x, the rightmost node contains five keys:

[k | m | r | s | x]

The middle key r is promoted to the parent.

Final B-Tree:

                  [f | j | r]
                /     |    |    \
[a | b | d | e] [g | h | i] [k | m] [s | x]

Conclusion: B-Tree maintains its properties by splitting overflowing nodes and promoting the middle key to the parent.


 

8. a) What is heap? 

b) Explain with an example how to construct a heap.

c) Write an algorithm for heap sort. Also find the complexity of the algorithm. 

(2+5+8)

Answer 8  

Q.8 (a) What is Heap? (2 Marks)

Answer:

A Heap is a special tree-based data structure that satisfies the heap property. It is a complete binary tree in which elements are arranged in a particular order.

There are two types of Heap:

  1. Max Heap: The parent node is greater than or equal to its child nodes.
  2. Min Heap: The parent node is smaller than or equal to its child nodes.

Example of Max Heap:

        50
       /  \
     30    40
    /  \
   10   20

Q.8 (b) Explain with an example how to construct a Heap. (5 Marks)

Answer:

A Heap can be constructed by inserting elements one by one into a complete binary tree and maintaining the heap property.

Example: Construct a Max Heap using the following elements:

10, 20, 15, 30, 40

Step 1: Insert 10.

10

Step 2: Insert 20 and compare it with its parent. Swap 20 and 10.

   20
  /
10

Step 3: Insert 15.

    20
   /  \
 10    15

Step 4: Insert 30 and swap it with 10, then with 20.

       30
      /  \
    20    15
   /
 10

Step 5: Insert 40 and swap it with 20, then with 30.

       40
      /  \
    30    15
   /  \
 10   20

Final Max Heap:

       40
      /  \
    30    15
   /  \
 10   20

Thus, the Max Heap is constructed by maintaining the heap property after every insertion.

Q.8 (c) Write an algorithm for Heap Sort. Also find the complexity of the algorithm. (8 Marks)

Answer:

Heap Sort is a sorting technique based on the Heap data structure. It first constructs a Max Heap and then repeatedly removes the largest element to sort the array in ascending order.

Algorithm: HEAP_SORT(A, n)

  1. Start.
  2. Build a Max Heap from the given array.
  3. Repeat for i = n-1 down to 1:
    • Swap A[0] with A[i].
    • Reduce the heap size by 1.
    • Apply MAX_HEAPIFY(A, 0).
  4. Stop.

Algorithm: MAX_HEAPIFY(A, n, i)

  1. Set largest = i.
  2. Set left = 2*i + 1.
  3. Set right = 2*i + 2.
  4. If left < n and A[left] > A[largest], then set largest = left.
  5. If right < n and A[right] > A[largest], then set largest = right.
  6. If largest != i, then:
    • Swap A[i] and A[largest].
    • Call MAX_HEAPIFY(A, n, largest).
  7. Return.

Complexity of Heap Sort:

Case Time Complexity
Best Case O(n log n)
Average Case O(n log n)
Worst Case O(n log n)

Space Complexity: O(1) auxiliary space for the iterative heap sort implementation.

Conclusion:

Heap Sort is an efficient sorting algorithm. Its time complexity in best, average and worst cases is O(n log n).



Q.9 (a) Explain Prim’s Algorithm with a suitable example to find the Minimum Spanning Tree. (7 Marks)

Answer:

Prim’s Algorithm:

Prim’s algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, weighted, undirected graph.

A Minimum Spanning Tree is a tree that connects all vertices of a graph with the minimum possible total edge weight and contains no cycle.

Steps of Prim’s Algorithm:

  1. Start from any vertex of the graph.
  2. Select the minimum-weight edge connecting a visited vertex to an unvisited vertex.
  3. Add the selected edge to the Minimum Spanning Tree.
  4. Mark the new vertex as visited.
  5. Repeat the process until all vertices are included in the MST.

Example:

Consider a graph having the following weighted edges:

Edge Weight
A-B 2
A-C 3
B-C 1
B-D 4
C-D 5
C-E 6
D-E 2

Starting from vertex A:

  1. Select A-B with weight 2.
  2. Select B-C with weight 1.
  3. Select B-D with weight 4.
  4. Select D-E with weight 2.

Minimum Spanning Tree:

Selected edges = A-B, B-C, B-D, D-E

Total minimum cost = 2 + 1 + 4 + 2 = 9

Therefore, the minimum cost of the spanning tree is 9.


Q.9 (b) What is an ADT? Find BFS traversal and show Queue operations. (8 Marks)

1. Abstract Data Type (ADT)

An Abstract Data Type (ADT) is a logical description of a data type that specifies the data and the operations that can be performed on it, without specifying how these operations are implemented.

Examples of ADT:

  1. Stack ADT
  2. Queue ADT
  3. List ADT
  4. Tree ADT

Queue ADT: A queue follows the FIFO (First In First Out) principle. The element inserted first is removed first.

Main operations:

  • Insert (Enqueue): Adds an element to the rear of the queue.
  • Remove (Dequeue): Removes an element from the front of the queue.

2. Breadth First Search (BFS)

Breadth First Search (BFS) is a graph traversal technique in which vertices are visited level by level. It uses a Queue data structure.

Algorithm for BFS:

  1. Start from the initial vertex V1.
  2. Mark V1 as visited and insert it into the queue.
  3. Remove a vertex from the front of the queue.
  4. Visit all its unvisited adjacent vertices and insert them into the queue.
  5. Repeat until the queue becomes empty.

3. BFS Traversal of the Given Graph

Starting vertex = V1

The adjacent vertices are considered from left to right.

BFS Traversal:

V1 → V2 → V3 → V4 → V5 → V6 → V7 → V8

4. Queue Operations During BFS

Step Remove (Dequeue) Insert (Enqueue) Queue after operation
Initial — V1 V1
1 V1 V2, V3 V2, V3
2 V2 V4, V5 V3, V4, V5
3 V3 V6, V7 V4, V5, V6, V7
4 V4 V8 V5, V6, V7, V8
5 V5 — V6, V7, V8
6 V6 — V7, V8
7 V7 — V8
8 V8 — Empty

Final BFS Traversal:

V1, V2, V3, V4, V5, V6, V7, V8

Conclusion: BFS visits all vertices level by level using the Queue ADT, which follows the FIFO principle.


Reactions