0% found this document useful (0 votes)
8 views29 pages

Winter 2021 Solution - Ds

Uploaded by

kamaliyasandip7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views29 pages

Winter 2021 Solution - Ds

Uploaded by

kamaliyasandip7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

DS WINTER 2021 SOLUTION

Q1 (A) What is Time Complexity? Explain with example (3M)


ANS

Time Complexity
 Time Complexity is the amount of time taken by the program for
execution As it is difficult to measure the time complexity in terms of
clockunits , we can measure the time complexity using the frequency
count.
Example
1. void display( )
{

z
int a, b, c;
a = 10;
aa
b = 20;
Aw

c = a + b;
print(“%d”, c);
}
ut

Solution
gr

Code Frequency Count


Ja

a = 10 1
b = 20 1
c=a+b 1
printf(“%d”, c) 1
Total 4

2. for(i = 1; i < = n; i ++)


for(j = 1; j < = n; j ++)
a=a+2
Statement Frequency Code
i=1 1
i<=n n+1
i ++ n
j=1 n

Click :Youtube Channel | Free Material | Download App


j<=1 n(n + 1)
j ++ n. n
a=a+2 n. n
total 3n2 + 4n + 2

Q1 (B) Explain malloc & free functions in C. Also discuss advantages of
dynamic over static memory allocation (4M)

ANS
Malloc
 The malloc” or “ memory allocation”. Method in c is used to
dynamically allocate a single large block of Memory with specified size.
 It returns a pointer of type void which can be cast into a pointer of
anyForm
 It doesn’t initialize memory at execution time So that it has initialized

z
aa
each block with the default garbage value initially
 Syntax :- ptr = ( cast_type *) malloc ( byte_size )
Aw

Free
 ‘free’ methed in c. is used to dynamically allocate the memory. The
ut

memory allocated usinf functions malloc() and calloc () is not de-


alloc on their own.
gr

 Hence the free() method is used whenever the dynamic memory


allocation takes place. It help t o reduce wastage of memory by
Ja

freeing it
 Syntax : free(ptr)

Advantages of dynamic over static memory allocation


 In dynamic memory allocation , when memory is allocated the
memory size can be changed.
 Dynamic memory allocation is done during program execution.
 In this allocated memory can be released at any time during the
program.
 This memory allocated at run time.

Click :Youtube Channel | Free Material | Download App


Q1 (C) Explain following (7M)

ANS

1. Priority Queue
 A priority queue is type of queue that arranged elements based
ontheir priority values elements with higher priority values are
typically retrieved before elements with Lower priority value.
2. Primitive Data Structure
 Primitive data structures is a Fundamental type of data
structuresthat store the data of only one type .
 Examples : int , float , char
3. Non – Primitive Data Structure
 The Non-Primitive Data Structure is a type of data structure

z
which is a user-defined that store the data of different types ina
single entity. aa
 Examples : structure, union and enumerated
Aw
4. Linear Data Structures
 Linear data Structure are the data Structure in which data is
arranged in a list or in a straight sequence.
ut

 For Example : arrays , list


5. Non Linear Data Structures
gr

 Non – Linear Data Structures are the data structure in which


Ja

data may be arranged in hierarchical manner.


 For Example : Trees , graphs
6. Application of Stack
 Expression evaluation
 Storing Function Calls
 Reversing a string
 Decimal to binary conversion
7. Sparse Matrix
 A sparse matrix is matrix in which many or most of elements
have value of zero
 Example

Click :Youtube Channel | Free Material | Download App


Q2(A) Write an algorithm for infix to prefix conversion (3M)

ANS
Algorithm
1. Scan all the symbols one by one from left to right in the given infix
Expression
2. If the reading symbol is operand , then immediate append it to the
postfixExpression.
3. If the reading symbol is left parenthesis ‘(’ , then push it onto the
stack.
4. If the reading symbol is right parenthesis ‘)’ , then pop all the
contents of thestack until the respective left parenthesis is popped
and append each popped symbol to postfix expression.

z
aa
5. If the reading symbol is operator ( + , - , * , / ) then push it onto the
stack. However, first pop the operators which are already on the
Aw
stack that have higheror equal precedence than the current
operator and append then to the postfix if open parenthesis is there
on top of the stack then, push the operator into the stack
ut

6. If input is over, pop all remaining symbol from stack & append then
gr

to postfix
Ja

Q2(B) Write algorithm to evaluate postfix expression explain working of


algorithm using appropriate example (4M)

ANS
Algorithm
1. Create a stack of store operands
2. Scan the given expression from left to right
3. a) If the scanned character is on operand push it into the stack
b) If scanned character is an operator, pop 2 operands from
stack & perform operator and push result back to the stack
4. Repeat step 3 till the characters are scan
5. When the expression is ended, the number the stock is the
final result

Click :Youtube Channel | Free Material | Download App


Example
456 * +
Step Input symbol operation stack calculate
1 4 push 4
2 5 push 4, 5
3 6 push 4, 5, 6
4 * pop(2 elements) 4 5*6
& evaluate
5 push result(30) 4, 30
6 + pop(2elements) empty 4+30
& evaluate
7 push result(34) 34
8 no more elements empty 34

Q2(C) Write C program to reverse string using stack (7M)

z
ANS
C program to reverse string using stack aa
Program
Aw
#include <stdio.h>
#include <string.h>
#define size 20
ut

Int top = -1 ;
gr

Char stack [size];


Ja

Char push (char ch)


{
if (top = = (size – 1)) {
printf(“stack is overflow\n”);
}
else
stack[++top] = ch;
}
Char pop( )
}
If(top= = - 1) {
Printf (“ stack is underflow\n”);
}
Else {
Return stack[top- -];
}

Click :Youtube Channel | Free Material | Download App


Int main( )
{
char str[207] ;
Int I;
Printf (“ enter the string : \n”,;
Geta (str) ;
[r(i=0; I < strlen(str); I + + )
{
Push ( str[i]);
}
Fr ( 1=0; i< strlen(str); ( + + )
{
Str[i] = pop( );
}
Priotf(“ reversed string is ;”);

z
Puts(str); aa
}
Output :
Aw

Enter string : yash


Reversed string is : hsay
ut

OR
gr

Q2(C) Write algorithm (i) insert & (ii) delete elements in circular queue
Ja

(7M)

Insertion
 Step 1 :
If (REAR + 1) % MAX = FRONT
Write “OVERFLOW”
go to step 4
[ END OF IF ]
 Step 2 :-
IF FRONT = -1 and REAR = -1
set FRONT = REAR = 0
else if REAR = MAX – 1 and FRONT! = 0
set REAR = 0
Else
Set REAR = ( REAR + 1 ) % MAX

Click :Youtube Channel | Free Material | Download App


[ END OF if ]
 Step 3 :- set queue [ REAR ] = val
 Step 4 :- Exit

Deletion
 Step 1 :-
If FRONT = -1
Write “ UNDERFLOW ”
Go to step 4
[ END OF IF ]
 Step 2 :- SET VAL = Queue [ FRONT ]
 Step 3 :-
IF FRONT = REAR
Set Front = Rear = -1
else if front = max – 1
Set Front = 0

z
else
set front = front + 1
[ END OF IF ]
aa
 Step 4 :- Exit
Aw

Q3(A)Write user defined c function to insert node at specific location


ut

in singly linked list (3M)


gr

ANS
Ja

Program
int insertatpos (struct node *head)
{
int i, choice, i=0;
Printf (“Do you want to enter any other element Loor/”);
Scanf (“%d”, &i);

if ( i = = 1 )
{
Printf ( “ Enter position:”);
Scanf(“%d”, &i);
}
else
{

Click :Youtube Channel | Free Material | Download App


return 0;
}
struct node * newnode = ( struct node * ) malloc
( size of ( strict node ) );
Struct node * temp,* ptr;
Printf ( “Enter element:”);
Scanf(“%d”, & newnode→data );
temp = head;
While ( choice >j)
{
ptr= temp;
temp=
temp→next;
j++;
}
newnode→ next = temp;

z
ptr→ next = newnode; aa
}
Aw

Q3(B) Write user defined C function to delete node from end in circular
linked list (4M)
ut

ANS
gr
Ja

Program
Void last_delete ( struct node*head)
{
Struct node *ptr, *preptr;
if ( head = = NULL )
{
Printf (“\n underflow\n”);
}
else if( headnext →= = head)
{
head = NULL;
free(head);
Printf(“\n node deleted\n”);
}
Else

Click :Youtube Channel | Free Material | Download App


{
ptr = head;
while (ptr→next ! = head)
{
preptr = ptr;
ptr = ptr→next;
}
Preptr→next.ptr→next;
free(ptr);
Printf(“\n node deleted\n”);
}
}

Q3(C) Write user defined C function to delete node from end in circular
linked list (7M)

z
ANS
aa
Aw
Program
#include<stdio,h>
#include<stdlib,h>
ut

struct Node
gr

{
int data;
Ja

struct node * next;


};
struct node * front ;
struct node * rear ;
void insert( );
void delete ( );
void display ( );

void main( )
{
int choice ;
while(choice 1 =4 )
{
Printf(“\n1. Insert \n2 delete \n3
display)Printf(“\n Enter the choice”);
Scanf(“%d”, &choice);
Switch (choice)

Click :Youtube Channel | Free Material | Download App


{ Case1:
Insert( );
break;
Case2:
delete( );
break;
Case3:
Display( );
break;
default:
Printf(“\n Enter valid choice? /n”);
}
}
}
void insert( )
{
struct node * ptr;

z
int item;
aa
ptr = (struct node * ) malloc(size of (struct node));
if(ptr = = NULL)
Aw
{
printf(“\n overflow\n”);
return;
}
ut

else
gr

{
printf(“\n enter value?\n”);
Ja

scanf(“%d”, &item);
ptr → data = item;
if(front = = NULL)
{
front = ptr;
rear = ptr;
front → next = NULL;
rear → next = NULL;
}
else
{
rear → next = ptr
rear = ptr;
rear → next = NULL;
}
}

Click :Youtube Channel | Free Material | Download App


}
void delete( )
{
Struct node * ptr;
if ( front = = NULL);
{
Printf(“\n underflow\n”);
return;
}
else
{ ptr = front;
front = front next;
free(ptr);
}
}
void display ( )
{

z
Struct node * ptr;
ptr = front;
if ( front = = null)
aa
Aw
{ printf(“\n Empty Queue\n”);
}
Else
{
ut

printf (“\n printing values ….. \n’);


While ( ptr! = NULL)
gr

{
Ja

Printf(“ \n %d \n”, ptr→data);


Ptr = ptr→next;
}
}
}

Click :Youtube Channel | Free Material | Download App


OR
Q3(A) Write user defined C function to insert node at end in circular
linked list (3M)

ANS

PROGRAM :
Void lastinsert ( struct node * ptr, struct node * temp,int item)
{
ptr = ( struct node * ) malloc ( size of ( structuralnode ));
if ( ptr = = NULL)
{
Printf(“\n overflow\n”);
}
else

z
{
Ptrdata = item;
if ( head = = NULL )
aa
{
Aw
head = ptr;
ptrnext = head;
}
ut

else
{ temp = head;
gr

While ( tempnext 1 = head )


{
Ja

Tempnext = ptr;
Ptrnext = head;
}
}
}

OR
Q3(B) Write user defined C function to delete node from specific
location in doubly linked list

ANS
Program
void delfrom pos ( )
{
int pos, i = 1;

Click :Youtube Channel | Free Material | Download App


struct node * temp;
temp = head;
Printf (“Enter position:”);
Scanf (“%d”, &pos);
While ( i< pos )
{
temp = tempnext;
i++;
}
temppervnext = tempnext;
tempnext perv =
tempprev;free ( temp );

OR
Q3(C) Write C program to implement stack using linked list (7M)

ANS

z
Program
#include <stdio.h>
aa
Aw
#include <stdlib.h>
Void push ( );
Void pop( );
Void display( );
ut

Struct node {
gr

int val;
struct node * next;
Ja

};
Struct node * head;
Void main ( )
{
int choice = 0; While
(choice ! = 4)
{
Printf(“\n! push\n2. Pop\n3. Show.”);
Printf(“\n Enter your choice \n”);
Scanf(“%d”, &choice)
Switch ( choice )
{
Case1:
push() :
break( )
Case 2 :
pop( ) :

Click :Youtube Channel | Free Material | Download App


break( );
Case 3 :
Display( ) ;
break( );
Default :
printf(“Please Enter Valid Choice”);
};
}
}
void push ( )
{
int val;
Struct node * ptr = (struct node *) malloc(size of (
if (ptr = = null)
{
printf(“not able to push element”)
}
else

z
{
printf(“Enter value”);
scanf(“%d, &val);
aa
Aw
if (head = = NULL)
{
ptr val = val;
ptr next = NULL;
ut

head = ptr;
}
gr

else
{
Ja

ptrval = val;
ptrnext = head;
head = ptr;
}
printf(“Item pushed”);
}
}
}
void pop( )
{
int item;
struct node * ptr;
if ( head = = NULL)
{
printf(“Underflow”)
}
else

Click :Youtube Channel | Free Material | Download App


{

item = headval;
ptr = head
head = headnext;
Free( ptr );
Printf(“item popped”);
}
}
void display ( )
{
int i;
struct node * ptr;
ptr = head;
if ( ptr = = NULL )
{
Printf(“stack is empty\n”);
}

z
else
{ aa
printf(“printing stack elements\n”)
Aw
while ( ptr ! = NULL )
{
printf (“ %d\n” , ptrval);
ptr = ptrnext ;
ut

}
}
gr

}
Ja

Q4(A) Construct binary tree from traversals given below (3M)


Inorder : D, B, A, E , G, C, H, F, I
Preorder : A, B, D, C, E, G, F, H, I

ANS

Click :Youtube Channel | Free Material | Download App


z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


z
Q4(B) Write short note on AVL tree (4M)
aa
Aw

ANS
ut

AVL Tree
 AVL Tree is invented by GM Adelson Velsk and EM Landis in 1962.
gr

The Tree is named AVL Tree in honous of its inventors.


 AVL Tree can be defined as height balance binary search tree in which
Ja

each node is associate with a balance factor which is calculated by


subtree tthe height of its right sub tree from that of its sub-tree.
 Tree is said to be balanced if balance factor of each node is in
between -1 to 1 , otherwise , the AVL tree will be unbalanced and
need to be balanced.
 Balance Factor (K) = height (Leftck) – height (rightck)
 If balance factor of any node is 1. It means that the left sub tree is
onelevel higher than the right subtree.
 If balance factor of any node is 0. It means that the Left Subtree and
rightsubtree contain equal weight.
 If balance factor of any node is -1 , it means that the left subtree is
onelevel lower than the right subtree

Click :Youtube Channel | Free Material | Download App


 Example

Q4(C) Explain concept of B tree with suitable example & list of its
applications (7M)

z
ANS
aa
Aw
B Tree
 B-Tree is a specialized m-way tree in at can be widely used in disk
access.
ut

 A b- tree of order m can have at most m-I keys and m children


one of the main reason of using B-Tree is its capability to store
gr

large number of keys in a single node and large key values by


Ja

keeping the height of the tree relatively small.


 A b-tree of order m contains all the properties of an m way
tree inadditional ,it contains the following properties.
1. Every node in a B-Tree contains at most m child.
2. Every node in a B-Tree except the root node of the
leaf node at leastm/2 children.
3. The root nodes must have at least 2 nodes.
4. All leaf nodes must be at the same level.

 It is not necessary that, all the nodes contain the same number of
childrenbut, each node m have m/2 number of nodes

Click :Youtube Channel | Free Material | Download App


 Applications of B Trees
 B-tree is used to index the data and provide first access to
the actual data stored in a large database that is stored on a
disk is avery time consumable process
 Searching on un-indexed and unsorted data containing n
key valuesneed o(n) running in worst case. However if we
use b tree to this database it will be searched in o(log n) in
worst case

z
aa
OR : Q4(A) Construct binary search from following numbers :
Aw
38, 13, 51, 10, 12, 40, 84, 25, 89, 37, 66, 95 (3M)

ANS
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


z
aa
Aw
ut
gr
Ja

OR : Q4(B) Explain BFS & DFS (4M)

ANS
BFS
 BFS stands for Breadth first search it is also known as level order
traversal
 The queue data structure is used for the breadth first search traversal
 There are many ways to traverse a the graph but among them BFS is the
most commonly used apparands .It is a recursive algorithm to search all
thevertices of a tree or graph data structure
 BFS put every vertex of the graph into two categories visited and non-
visited

Click :Youtube Channel | Free Material | Download App


 It selects a single node in a graph and after that visits all the nodes
adjacent to the selected node
DFS
 DFS stands for depth first search
 In DFS traversal, the stack data structure is used which works on the
LIFO principle
 It is a recursive algorithm to search all the vertices of a tree data
structure ora graph
 The depth first search (DFS) algorithm starts with the initial node of
graph Gand goes deeper until we find the goal node or the node with
no children
 DFS algorithm can be used to implement the topological sarting
 It can be used to find the paths between two vertices

z
OR : Q4(C) Explain B + tree with example (7M)
aa
Aw

ANS

B+ tree
ut

 B + tree is an extension of B tree which allow efficient insertion, deletion


gr

and search operation


 In B tree, keys and records both can be stored in the internal as well as
Ja

leaf nodes, where as B + tree records can only be stored on the leaf
nodeswhile internal nodes can only store the keys value
 The leaf node of a B + tree are linked together in the form of singly
linkedlist to make the search queries more efficient
 B + tree are used to store the large amount data which cannot be stored
inthe main memory. Due to fact that, size of main memory is always
limited. The internal node of the B + tree are in the main memory where
as, leaf node are in the secondary memory
 The internal nodes of the B+ tree are often index nodes . A B+ nodes of
order three is shown in following figure

Click :Youtube Channel | Free Material | Download App


 Advantage of B + tree :
1) Records can be fetched in equal number of disc access .
2) Heighted of the tree remains balanced and less as compared to B
tree .
3) Keys are used for indexing
4) We can access the data stored in a B+ tree sequentially as well as
directly
5) Faster search queries as the data is stored only on the leaf nodes

Q5(A) Explain Prim’s Algorithm (3M)

ANS

z
Prim’s Algorithm
aa
 Prim’s algorithm is a greedy algorithm that is used to find the
minimum spanning tree from a graph prim’s algorithm finds the
Aw
subset of edges that includes every vertex of the graph such that
sum of weights of edges can be minimized .
 Prim’s algorithm starts with the single node and explores all the
ut

adjacent nodes with all the connecting edges at every step . The
gr

edges with the minimal weights causing no cycles in the graph got
selected .
Ja

 Applications
 Prim’s algorithm can be used in network designing
 It can be used to make network cycle
 It can also be used to lay down electrical wiring cables

Q5(B) Write C program for selection sort (4M)

ANS

Program
# include <stdio.h>
Void selection (int arr[],int n)
{
int i ,j,small;
For (i=0,i<n-1,i++)

Click :Youtube Channel | Free Material | Download App


{
small=i;
for (j=i+1; j<n;j++)
{
if (arr[j]<arr[small])
{ small = j;
}
}
int temp = arr[small];
arr[small] = arr [i];
arr[i] = temp;
}
}
void printArr (int a[], intn)
{

z
int i;
for ( i = 0; i<n; i++)
Printf(“%d”,a[i]);
aa
Aw
}
int main()
{
ut

int a[] = {12, 31, 25, 8, 32, 17};


int n = size of (a) /size of (a[0]);
gr

printf(“ Before sorting array element are \n”);


Ja

printArr(a,n);
selection(a,n);

printf (“\n After sorting array elements are \n”) ;


printArr(a,n);
return 0 ;
}

Click :Youtube Channel | Free Material | Download App


Q5(C) List out different hash methods & explain any three (7M)

ANS

 There are five types of hash functions that are used to place record in
hash table
1) Division Method
2) Midsquare Method
3) Multiplicative Hash Function
4) Digit Folding
5) Digit Analysis
 Division Method
 Hash function depends upon remainder of division

z
 Typically divisor is table length aa
H(key) = key mod M
H(key) = record % table size
Aw

54, 72, 89, 37


h(key) = 54 % 10 = 4
h(key) = 72 % 10 = 2
ut

h(key) = 89 % 10 = 9
gr

h(key) = 37 % 10 = 7
Ja

Click :Youtube Channel | Free Material | Download App


 Midsquare Method
 In mid square method, key is squared & middle or mid part of
result is used as index
 If key is string, it has to preprocessed to produce by number
 Consider that if we want to place record 3111
31112 = 9678321
From hash table of size 1000
H(3111) = 783
 Multiplicative Hash Function
 Given record is multiplied by some constant value. Formula for
computing hash key is
H(key) = floor(p * (fractional part of A)) where p is integer
constant & A is constant real number
Donald length suggested to use constant
A = 0.61803398987

z
If key = 170 and p = 50 then aa
H(key) = floor(50 *(107 * 0.61803398987)
H(key) = floor(3306.4818458045)
Aw

H(key) = 3306

OR Q5(A) Define terms with respect to file : fields, records (3M)


ut
gr

ANS
Ja

Fields
 A combination of one or more characters is called field. It is smallest
unit of data that can be accessed by user name of each field a record
is unique
Records
 A collection of related fields treated at single as single unit is called
record
Database
 A database is information that is set up for easy access, management
& updating

Click :Youtube Channel | Free Material | Download App


OR Q5(B) Compare Sequential & Binary Search methods (4M)

ANS

Sequential Search Binary Search


Time Complexity is 0(n) Time Complexity is 0(logn)
Sequence of elements in Element must be sorted in container
container does not effect
Algorithm is iterative in nature Algorithm technique is divide &
conquer

OR Q5(C) Apply quick sort for following data : 9,7, 5, 11, 12, 2, 14, 3, 10, 6
(7M)

z
ANS aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App

You might also like