0% found this document useful (0 votes)
9 views

dsa assign 3 sol

dsa mod 4 and 5 vtu

Uploaded by

pavan.k17819
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

dsa assign 3 sol

dsa mod 4 and 5 vtu

Uploaded by

pavan.k17819
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1) Design an algorithm to traverse a graph using Depth First Search (DFS).

Apply DFS for


the graph given below.

Depth First Search (DFS) Algorithm

1. Initialize:
o Create a stack and push the starting node onto the stack.
o Create a set to keep track of visited nodes.
2. DFS Algorithm:
o While the stack is not empty:
 Pop a node from the stack.
 If the node has not been visited:
 Mark the node as visited.
 Push all adjacent nodes that have not been visited onto the stack.
3. End:
o The algorithm ends when the stack is empty, and all reachable nodes from the
starting node have been visited

2) Construct a binary tree from the Post-order and In-order sequence given below
In-order: GDHBAEICF
Post-order: GHDBIEFCA
Sol) in order traversal – left root right
pre order – root left right
post order left right root
3) What is a Priority queue? Demonstrate functions in C to implement the Max Priority
queue with an example. i) Insert into the Max priority queue ii) Delete into the Max
priority queue iii) Display Max priority queue
A Priority Queue is a data structure where each element has a priority assigned to it.
Elements with higher priority are served before elements with lower priority. In a Max
Priority Queue, the element with the highest priority is always at the front and is dequeued
first.

// Function to insert an element into the Max Priority Queue


void insert(int value) {
if (size == MAX) {
printf("Priority Queue is full\n");
return;
}

size++;
int i = size - 1;
priorityQueue[i] = value;

while (i != 0 && priorityQueue[(i - 1) / 2] < priorityQueue[i]) {


swap(&priorityQueue[i], &priorityQueue[(i - 1) / 2]);
i = (i - 1) / 2;
}
}

// Function to delete the maximum element from the Max Priority Queue
int deleteMax() {
if (size <= 0) {
printf("Priority Queue is empty\n");
return -1;
}

if (size == 1) {
size--;
return priorityQueue[0];
}

int root = priorityQueue[0];


priorityQueue[0] = priorityQueue[size - 1];
size--;
heapify(0);

return root;
}

// Function to display the Max Priority Queue


void display() {
if (size <= 0) {
printf("Priority Queue is empty\n");
return;
}

for (int i = 0; i < size; i++)


printf("%d ", priorityQueue[i]);
printf("\n");
}
4) Define hashing. Explain different hashing functions with examples. Discuss the
properties of a good hash function.
### Hashing

**Definition**: Hashing is a technique used to map data of arbitrary size to fixed-size


values, typically for fast data retrieval. It involves using a hash function to convert a given
key into a hash value, which is then used as an index to store the corresponding data in a
hash table.

### Hash Functions

1. **Division Method**:
- **Description**: This method divides the key by a prime number `M` and uses the
remainder as the hash value.
- **Formula**: `h(x) = x mod M`
- **Example**: For a key `2345` and `M = 100`, the hash value is `2345 mod 100 = 45`.

2. **Mid-Square Method**:
- **Description**: The key is squared, and a portion of the resulting digits is used as the
hash value.
- **Formula**: `h(x) = middle digits of (x^2)`
- **Example**: For a key `1234`, the square is `1522756`. Taking the middle two digits,
the hash value is `27`.

3. **Folding Method**:
- **Description**: The key is divided into equal parts, and the parts are added together to
form the hash value.
- **Steps**:
1. Divide the key into parts.
2. Add the parts together.
- **Example**: For a key `123456`, divide it into `123` and `456`. The hash value is `123 +
456 = 579`.

### Properties of a Good Hash Function

1. **Uniform Distribution**: The hash function should distribute keys uniformly across the
hash table to minimize collisions.
2. **Deterministic**: The same key should always produce the same hash value.
3. **Efficient Computation**: The hash function should be quick to compute.
4. **Minimize Collisions**: The function should minimize the number of collisions, where
different keys produce the same hash value.
5. **Non-reversible**: It should be difficult to reverse-engineer the original key from the
hash value.

5) What is dynamic hashing? Explain the following techniques with examples: i) Dynamic
hashing using directories ii) Directory less dynamic hashing
### Dynamic Hashing

**Definition**: Dynamic hashing is a technique used to dynamically adjust the size of the
hash table as the number of elements increases or decreases. This helps in efficiently
handling collisions and maintaining performance.

Dynamic hashing using directory


• Uses a directory of pointers to buckets/bins which are collections of records
• The number of buckets are doubled by doubling the directory, and splitting just the bin
that overflowed.
• Directory much smaller than file, so doubling it is much cheaper.
Directory less Dynamic hashing Basic Idea:
• Pages are split when overflows occur – but not necessarily the page with the overflow.
• Directory avoided in Linear hashing by using overflow pages. (chaining approach)
• Splitting occurs in turn, in a round robin fashion.one by one from the first bucket to the
last bucket.
• Use a family of hash functions h0, h1, h2, ...
• Each function’s range is twice that of its predecessor.
• When all the pages at one level (the current hash function) have been split, a new level is
applied.
• Insert in Order using linear hashing: 1,7,3,8,12,4,11,2,10 • After insertion till 12:
6) Define selection tree. Construct min winner tree for the runs of a game given below.
Each run consists of values of players. Find the first 5 winners.

7) Define Binary Search tree. Construct a binary search tree (BST) for the following
elements: 100, 85, 45, 55, 120, 20, 70, 90, 115, 65, 130, 145. Traverse using in-order,
pre-order, and post-order traversal techniques. Write recursive C functions for the
same.

Definition: A Binary Search Tree (BST) is a binary tree in which each node has at most two
children, referred to as the left child and the right child. For each node:

 The left subtree contains only nodes with keys less than the node's key.
 The right subtree contains only nodes with keys greater than the node's key.
 Both the left and right subtrees must also be binary search trees.

void inorder(NODE root)


{
if(root!=NULL)
{
inorder(root->lchild);
printf("%d",root->data);
inorder(root->rchild);
}
}

void preorder(NODE root)


{
if(root!=NULL)
{
printf("%d",root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}

void postorder(NODE root)


{
if(root!=NULL)
{
postorder(root->lchild);
postorder(root->rchild);
printf("%d",root->data);
}
}
8)

### Min Leftist Tree

A **Min Leftist Tree** is a type of binary tree that maintains two properties:
1. **Heap Property**: For any given node, the value of the node is less than or equal to the
values of its children. This ensures that the minimum value is always at the root.
2. **Leftist Property**: For any given node, the rank (or null path length, npl) of the left child
is greater than or equal to the rank of the right child. The rank of a node is the length of the
shortest path to a node without two children (a null node).

### Meld Operation


To meld two min leftist trees, follow these steps:
1. **Compare the Roots**: The root with the smaller value becomes the new root.
2. **Recursively Meld**: Meld the right subtree of the new root with the other tree.
3. **Ensure Leftist Property**: Swap the left and right children if necessary to maintain the
leftist property.

9) What is chained hashing? Discuss its pros and cons. Construct the hash table to insert
the keys: 7, 24, 18, 52, 36, 54, 11, 23 in a chained hash table of 9 memory locations. Use
h(k) = k mod m.
A leftist tree is a type of binary tree that is biased to the left. In a leftist tree, the null path
length (NPL) of the left child is always greater than or equal to the NPL of the right child. The
NPL of a node is the length of the shortest path from that node to a node without two
children. This property ensures that the tree remains balanced towards the left, making
operations like merging more efficient.
Declaration in c
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a node in the leftist tree


struct Node {
int key;
struct Node* left;
struct Node* right;
int npl; // Null Path Length
};

// Function to create a new node


struct Node* createNode(int key) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->key = key;
newNode->left = NULL;
newNode->right = NULL;
newNode->npl = 0;
return newNode;
}

11) Define Forest. Transform the given forest into a Binary tree and traverse using
inorder, preorder and postorder traversal.
a forest is a collection of disjoint trees. Unlike a single tree, which has one root node
and a hierarchical structure, a forest consists of multiple trees, each with its own root
and hierarchy.
12) Define the Disjoint set. Consider the tree created by the weighted union function
on the sequence of unions: union(0,1), union(2,3), union(4,5), union(6,7), union(0,2),
union(4,6), and union(0,4). Process the simple find and collapsing find on eight finds
and compare which find is efficient.

You might also like