Lab Manual DS StudentFile
Lab Manual DS StudentFile
STRUCTURE_USING C
LAB MANUAL
KCS – 351
Prepared by
Dr. Paramita De
1
List of Experiments
Minimum Ten / Eight experiments to be performed (As per syllabi)
2
Objective : - Implement Bubble Sort.
Theory:
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in
which each pair of adjacent elements is compared and the elements are swapped if they are not in
order. This algorithm is not suitable for large data sets as its average and worst case complexity are
2
of Ο(n ) where n is the number of items.
Algorithm:
begin BubbleSort(list)
return list
end BubbleSort
Program:
#include<stdio.h>
int i,j,t;
for(i=0;i<max;i++){
for(j=0;j<max-i-1;j++){
if(a[j]>a[j+1]){
3
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
int i;
for(i=0;i<max;i++)
printf("%d ",a[i]);
main()
int i,ch,yn,max;
int a[10];
scanf("%d",&max);
for(i=0;i<max;i++)
scanf("%d",&a[i]);
Bubble_sort(a,max);
4
display(a,max);
Output:
13479
Viva Questions:
1. What is the output of bubble sort after the 2nd pass given the following sequence of
numbers: 25 57 48 37 12 92 86 33 23 15?
5. What are the correct intermediate steps of the following data set when it is being sorted with
the bubble sort? 15,20,10,18.
Theory:
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based
algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted
part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost element,
and that element becomes a part of the sorted array. This process continues moving unsorted array
boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case complexities are of
2
Ο(n ), where n is the number of items.
Algorithm:
for i = 1 to n - 1
/* set current element as minimum*/
min = i
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
Program:
#include<stdio.h>
int i1,k,m;
m=a[j];k=0;
for(i1=j;i1<n;i1++){
if(a[i1]<=m){
m=a[i1];
k=i1;
return(k);
int i,l,t,j;
for(i=0;i<n;i++){
l=min(a,i,n);
t=a[i];
7
a[i]=a[l];
a[l]=t;
for(j=0;j<n;j++)
printf("%d ",a[j]);
void main()
int a[10],n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
select(a,n);
Output:
8
Enter the size of the array 5
13479
Viva Questions:
1. What is the output of selection sort after the 1st iteration given the following sequence of
numbers: 14 9 4 18 45 2 37 63?
3. In a selectionsort of n elements, how many times is the swap function called in the complete
execution of the algorithm?
Theory:
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list
(in the same array). This algorithm is not suitable for large data sets as its average and worst case
2
complexity are of Ο(n ), where n is the number of items.
Algorithm:
end for
end procedure
Program:
10
#include<stdio.h>
int i,j,t;
for(i=1;i<max;i++){
t=a[i];
a[j+1]=a[j];
a[j+1]=t;
int i;
for(i=0;i<max;i++)
printf("%d ",a[i]);
main()
int i,ch,yn,max;
int a[10];
scanf("%d",&max);
11
printf("\nEnter the elements:\n");
for(i=0;i<max;i++)
scanf("%d",&a[i]);
Insertion_sort(a,max);
display(a,max);
Output:
13479
Viva Questions:
5. What is the output of insertion sort after the 1st iteration given the following sequence of
numbers: 7 3 5 1 9 8 4 6?
12
Objective : - Implement Merge Sort.
Theory:
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time
complexity being Ο(n log n), it is one of the most respected algorithms. Merge sort first divides the
array into equal halves and then combines them in a sorted manner.
Algorithm:
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = l+ (r-l)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
Merge(arr[], l, m, r)
1. Set i=l, j= m+1,k=0
2. Repeat while (i<= m) and(j<=r)
if(arr[i]<arr[j])
set temp[k]=arr[i]
i=i+1
else
Set temp[k]=arr[j]
j=j+1
3. if i>m
Repeat while j<=r
set temp[k]=arr[j]
k=k+1
j=j+1
else
repeat while j<=m
set temp[k]=arr[j]
k=k+1
j=j+1
Program:
13
#include<stdio.h>
int i,j,k,h;
int b[10];
i=low;h=low;j=mid+1;
if(a[h]<=a[j]){
b[i]=a[h];
h++;
else{
b[i]=a[j];
j++;
i++;
if(h>mid){
for(k=j;k<=high;k++){
b[i]=a[k];
i++;
else{
for(k=h;k<=mid;k++){
14
b[i]=a[k];
i++;
for(k=low;k<=high;k++)
a[k]=b[k];
int m;
if(l<h){
m=(l+h)/2;
Merge_sort(a,l,m);
Merge_sort(a,m+1,h);
Merge(a,l,m,h);
int i;
for(i=0;i<max;i++)
printf("%d ",a[i]);
15
}
main()
int i,ch,yn,max;
int a[10];
scanf("%d",&max);
for(i=0;i<max;i++)
scanf("%d",&a[i]);
Merge_sort(a,0,max-1);
display(a,max);
Output:
13479
16
Viva Questions:
4. What is the output of merge sort after the 1st pass given the following sequence of numbers:
25 57 48 37 12 92 86 33?
5. What is the output of merge sort after the 2nd pass given the following sequence of numbers:
25 57 48 37 12 92 86 33?
Theory: QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions
the given array around the picked pivot. There are many different versions of quickSort that pick
pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot
3. Pick a random element as pivot.
4. Pick median as pivot.
The key process in quickSort is partition(). Target of partitions is, given an array and an element x
of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller
than x) before x, and put all greater elements (greater than x) after x. All this should be done in
linear time.
Algorithm:
1. If(beg<end)
1. loc= Call partition(A, beg , end)
2. Call Quick_sort(A,beg,loc-1)
3. Call Quick_sort(A,loc+1,end)
Partition(A,beg,end)
1. If( beg<end)
Set pivot=A[beg]
Set i=beg
Set j=end
2. Repeat step 3 to 5 while (i<j)
3. Repeat while (A[i] <= pivot and i<end)
i++
4. Repeat while (A[j] >= pivot and j>0)
j--
5. If((i<j)
Swap A[i] with A[j]
6. If (i>j)
Swap A[beg] with A[j]
7. Return j
18
Program:
int i,j,t,tt,ii;
tt=a[m];
i=m;j=n;
while(i<=j){
while(a[i]<tt){
i=i+1;
while(a[j]>tt){
j=j-1;
if(i<=j){
t=a[i];
a[i]=a[j];
a[j]=t;
if(i>j){
t=a[m];
a[m]=a[j];
a[j]=t;
}
19
return j;
int i,j,t;
if(p<=q){
j=partition(a,p,q);
Quick_sort(a,p,j-1);
Quick_sort(a,j+1,q);
int i;
for(i=0;i<max;i++)
printf("%d ",a[i]);
main()
int i,ch,yn,max;
int a[10];
for(i=0;i<max;i++)
scanf("%d",&a[i]);
Quick_sort(a,0,max-1);
display(a,max);
Output:
13479
Viva Questions:
4. What is the output of quick sort after the 1st pass given the following sequence of numbers:
25 57 48 37 12 92 86 33?
5. What is the output of quick sort after the 2nd pass given the following sequence of numbers:
25 57 48 37 12 92 86 33?
21
Experiment No.: 3.1
Theory:
Linear search is a very simple search algorithm. In this type of search, a sequential search is made
over all items one by one. Every item is checked and if a match is found then that particular item is
returned, otherwise the search continues till the end of the data collection.
Algorithm:
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
end procedure
22
Program:
#include<stdio.h>
//#define max 5
//int a[max];
int i,l,flag=0;
for(i=0;i<max;i++){
if(a[i]==t){
flag=1;
break;
if(flag==1)
else
main()
int i,max,a[10],t;
scanf("%d",&max);
for(i=0;i<max;i++)
23
scanf("%d",&a[i]);
scanf("%d",&t);
Linear_search(a,max,t);
Output:
6 is present in location 4
Viva Questions:
24
Experiment No.: 3.2
Theory:
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search
algorithm works on the principle of divide and conquer. For this algorithm to work properly, the
data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection. If a
match occurs, then the index of item is returned. If the middle item is greater than the item, then the
item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for in
the sub-array to the right of the middle item. This process continues on the sub-array as well until
the size of the subarray reduces to zero.
Algorithm:
Procedure binary_search
4. if A[MID] = VAL
Set POS = MID
Print POS
Go to Step 6
else if A[MID] > VAL
set END = MID - 1
else
set BEG = MID + 1
[end of if]
[end of loop]
25
5. Step 5: IF POS = -1
PRINT "VALUE IS NOT PRESENT IN THE ARRAY"
[END OF IF]
6. Step 6: EXIT
Program:
#include<stdio.h>
//#define max 5
//int a[max];
int l,loc,flag=0,m,h;
l=0;h=max;
while(l<=h){
m=(l+h)/2;
if(t==a[m]){
loc=m+1;
flag=1;
break;
else if(t<a[m]){
h=m-1;
}
26
else if(t>a[m]){
l=m+1;
if(flag==1)
else
int m;
while(l<=h){
m=(l+h)/2;
if(a[m]==t){
return m;
else if(a[m]<t)
return R_Binary_search(a,m+1,h,t);
else
return R_Binary_search(a,l,m-1,t);
return -1;
}
27
main()
int i,yn,ch,max,a[10],t,m;
do{
scanf("%d",&ch);
scanf("%d",&max);
for(i=0;i<max;i++)
scanf("%d",&a[i]);
scanf("%d",&t);
switch(ch){
case 1: Binary_search(a,max,t);
break;
case 2: m=R_Binary_search(a,0,max-1,t);
if(m==-1)
else
printf("\nwant to continue\n");
28
scanf("%d",&yn);
}while(yn==1);
Output:
11
222
Viva Questions:
29
Experiment No.: 4
Theory:
A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates,
etc.
Algorithm:
Push ( ):
Description: Here STACK is an array with MAX locations. TOP points to the top most element and
ITEM is the value to be inserted.
3. Else
[End of If]
7. Exit
Pop ( ):
Description: Here STACK is an array with MAX locations. TOP points to the top most element.
2. Print: Underflow
3. Else
30
[End of If]
7. Exit
Program:
#include<stdio.h>
#define max 5
int top=-1;
if(top==max-1)
printf("Stack full");
else{
top=top+1;
s[top]=item;
int item;
if(top==-1){
printf("Stack empty");
return -1;
else{
item=s[top];
31
top=top-1;
return item;
int i;
for(i=top;i>=0;i--)
printf("\n%d",s[i]);
main()
int ch,st[max],item,yn;
while(1){
switch(ch){
scanf("%d",&item);
push(st,item);
break;
case 2: item=pop(st);
if(item>-1)
32
printf("\n The deleted item is: %d\n",item);
break;
case 3: display(st);
break;
scanf("%d",&yn);
if(yn==0)
break;
Output:
Viva Questions:
1. What is a stack?
Experiment No.: 5
34
Objective : - Implement queue using array.
Theory: Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is
open at both its ends. One end is always used to insert data (enqueue) and the other is used to
remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored
first will be accessed first.
Algorithm:
Insert Operation:
Steps:
Delete Operation:
Input : A que with elements. FRONT and REAR are two pointer of queue .
Output : The deleted element is stored in ITEM.
Data structure : Que is an array representation of queue structure.
35
Steps:
Program:
#include<stdio.h>
#define max 5
int front=-1;
int c=0;
if(rear==max-1)
printf("Queue full");
else{
36
if(c==0){
front=0;c++;
rear=rear+1;
q[rear]=item;
int item;
if(front==-1){
printf("Queue empty");
return -1;
else{
item=q[front];
front=front+1;
return item;
int i;
printf(" %d",q[i]);
main()
int ch,q[max],item,yn;
while(1){
switch(ch){
scanf("%d",&item);
insert(q,item);
break;
case 2: item=delete(q);
if(item>-1)
break;
case 3: display(q);
break;
scanf("%d",&yn);
38
if(yn==0)
break;
Output:
1 2 3
2 3
Viva Questions:
1. What is queue?
2. If the elements “A”, “B”, “C” and “D” are placed in a queue and are deleted one at a time, in
what order will they be removed?
3. A data structure in which elements can be inserted or deleted at/from both the ends but not
in the middle is?
4. What is the overflow condition of a normal queue, if implemented using an array of size
MAX_SIZE?
40
Experiment No.: 6
Theory:
Circular Queue is a linear data structure in which the operations are performed based on FIFO (First
In First Out) principle and the last position is connected back to the first position to make a circle.
Algorithm:
Program:
#include<stdio.h>
#define max 3
int front=-1;
int c=0;
printf("Queue full");
front=0;
rear=0;
q[rear]=item;
42
}
rear=0;
q[rear]=item;
else{
rear=rear+1;
q[rear]=item;
int item;
if(front==-1){
printf("Queue empty");
return -1;
item=q[front];
q[front]=0;
if(front == rear){
front=-1;rear=-1;
else if(front==max-1){
front=0;
43
}
else{
front=front+1;
return item;
int i;
for(i=0;i<max;i++)
printf(" %d",q[i]);
main()
int ch,q[max],item,yn;
while(1){
switch(ch){
scanf("%d",&item);
44
insert(q,item);
break;
case 2: item=delete(q);
if(item>-1)
break;
case 3: display(q);
break;
scanf("%d",&yn);
if(yn==0)
break;
Output:
Queue full
1 2 3
0 2 3
4 2 3
Viva Questions:
47
Experiment No.: 7
Theory:
The major problem with the stack implemented using array is, it works only for fixed number of
data values. That means the amount of data must be specified at the beginning of the
implementation itself. Stack implemented using array is not suitable, when we don't know the size
of data which we are going to use. A stack data structure can be implemented by using linked list
data structure. The stack implemented using linked list can work for unlimited number of values.
That means, stack implemented using linked list works for variable size of data. So, there is no need
to fix the size at the beginning of the implementation. In linked list implementation of a stack, every
new element is inserted as 'top' element. That means every newly inserted element is pointed by
'top'. Whenever we want to remove an element from the stack, simply remove the node which is
pointed by 'top' by moving 'top' to its next node in the list. The next field of the first element must
be always NULL.
Algorithm:
48
Step 7: Finally, delete 'temp' (free(temp)).
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
int info;
};
ptr->info=item;
if(top==NULL){
49
ptr->next=NULL;
top=ptr;
else{
ptr->next=top;
top=ptr;
int pop()
int item;
if(top==NULL){
printf("Stack empty");
return -1;
else{
item=top->info;
top=top->next;
return item;
void display()
ptr=top;
50
printf("\n The stack is:\n");
while(ptr!=NULL){
printf("\n%d",ptr->info);
ptr=ptr->next;
main()
int ch,item,yn;
while(1){
scanf("%d",&ch);
switch(ch){
scanf("%d",&item);
push(item);
break;
case 2: item=pop();
if(item>-1)
break;
case 3: display();
51
break;
scanf("%d",&yn);
if(yn==0)
break;
Output:
Viva Questions:
53
Experiment No.: 8
Theory:
The major problem with the queue implemented using array is, It will work for only fixed number
of data. That means, the amount of data must be specified in the beginning itself. Queue using array
is not suitable when we don't know the size of data which we are going to use. A queue data
structure can be implemented using linked list data structure. The queue which is implemented
using linked list can work for unlimited number of values. That means, queue using linked list can
work for variable size of data (No need to fix the size at beginning of the implementation). The
Queue implemented using linked list can organize as many data values as we want.
In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the
first node is always pointed by 'front'.
Algorithm:
54
Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until
'temp' reaches to 'rear' (temp → next != NULL).
Step 4: Finally! Display 'temp → data ---> NULL'.
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
int info;
};
ptr->info=item;
front=ptr;
rear=ptr;
}
55
else{
rear->next=ptr;
rear=rear->next;
rear->next=NULL;
int delete()
int item;
if(front==NULL){
printf("Queue empty");
return -1;
else{
item=front->info;
front=front->next;
return item;
void display()
int i;
while(ptr!=rear->next){
printf(" %d",ptr->info);
ptr=ptr->next;
main()
int ch,item,yn;
while(1){
switch(ch){
scanf("%d",&item);
insert(item);
break;
case 2: item=delete();
if(item>-1)
break;
case 3: display();
57
break;
scanf("%d",&yn);
if(yn==0)
break;
Output:
58
The queue is:
1 2 3
2 3
Viva Questions:
59
Experiment No.: 9
Algorithm:
enQueue(value) This function is used to insert an element into the circular queue. In a circular
queue, the new element is always inserted at Rear position.
Steps:
deQueue() This function is used to delete an element from the circular queue. In a queue, the
element is always deleted from front position.
Steps:
Program:
struct Node
{
int data;
struct Node* link;
};
struct Queue
{
struct Node *front, *rear;
};
q->rear = temp;
q->rear->link = q->front;
}
return value ;
}
61
printf("\nElements in Circular Queue are: ");
while (temp->link != q->front)
{
printf("%d ", temp->data);
temp = temp->link;
}
printf("%d", temp->data);
}
enQueue(q, 9);
enQueue(q, 20);
displayQueue(q);
return 0;
}
Output:
62
Experiment No.: 10.1
Objective : - Implement binary tree using linked list and show tree traversal result.
Theory: A Binary Tree is a type of data structure in which each node has at most two children (left
child and right child). Binary trees are used to implement binary search trees and binary heaps, and
are used for efficient searching and sorting. A binary tree is a special case of a K-ary tree, where k
is 2. Common operations for binary trees include insertion, deletion, and traversal. The difficulty of
performing these operations varies if the tree is balanced and also whether the nodes are leaf nodes
or branch nodes. For balanced trees the depth of the left and right subtrees ov every node differ by 1
or less. This allows for a predictable depth also known as height. This is the measure of a node from
root to leaf, where root is 0 and sebsequent nodes are (1,2..n). This can be expressed by the integer
part of log (n) where n is the number of nodes in the tree.
2
Algorithm:
Program:
#include<stdio.h>
#include<malloc.h>
int data;
}node;
node *create()
node *p;
int x;
scanf("%d",&x);
if(x==-1)
return NULL;
p=(node*)malloc(sizeof(node));
64
p->data=x;
p->left=create();
p->right=create();
return p;
if(t!=NULL)
int main()
node *root;
root=create();
return 0;
Output:
3417528
Viva Questions:
2. What are the two way to represent binary tree in memory?Which one do you prefer and why?
67
Experiment No.: 10.2
Objective : - Implement binary search tree using linked list and implement the tree traversals.
Theory:
A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
properties−
The left sub-tree of a node has a key less than or equal to its parent node's key.
The right sub-tree of a node has a key greater than to its parent node's key.
Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and
can be defined as −
left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)
Algorithm:
while(current->data != data){
if(current != NULL) {
printf("%d ",current->data);
//not found
if(current == NULL){
68
return NULL;
}
}
}
return current;
}
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
while(1) {
parent = current;
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
} //go to right of the tree
else {
69
current = current->rightChild;
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
int info;
};
if(root == NULL){
root->info=data;
70
root->left=NULL;
root->right=NULL;
return root;
else{
if(data<root->info)
root->left=create(root->left, data);
else
if(data>root->info)
root->right=create(root->right,data);
else
return root;
if(root!=NULL){
inorder(root->left);
printf("%d ",root->info);
inorder(root->right);
71
void preorder(struct node *root)
if(root!=NULL){
printf("%d ",root->info);
preorder(root->left);
preorder(root->right);
if(root!=NULL){
postorder(root->left);
postorder(root->right);
printf("%d ",root->info);
main()
int n,ch,i,d;
do{
scanf("%d",&ch);
switch(ch)
72
{
case 1: root=NULL;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&d);
root=create(root,d);
break;
case 2: inorder(root);
break;
case 3: preorder(root);
break;
case 4: postorder(root);
break;
case 5: printf("\nEnd");
break;
}while(ch!=5);
Output:
1234578
3124578
2187543
Viva Questions:
2. What is the speciality about the inorder traversal of a binary search tree?
74
Experiment No.: 11.1
Theory: There are many ways to traverse graphs. BFS is the most commonly used approach. BFS
is a traversing algorithm where you should start traversing from a selected node (source or starting
node) and traverse the graph layerwise thus exploring the neighbour nodes (nodes which are
directly connected to source node). You must then move towards the next-level neighbour nodes.
As the name BFS suggests, you are required to traverse the graph breadthwise as follows:
1. First move horizontally and visit all the nodes of the current layer
2. Move to the next layer
Algorithm:
Step 4: If the removed node has unvisited child nodes, mark them as visited and insert the unvisited
children in the queue.
let Q be queue.
Q.enqueue( s ) //Inserting s in queue until all its neighbour vertices are marked.
mark s as visited.
while ( Q is not empty)
//Removing that vertex from queue,whose neighbour will be visited now
v = Q.dequeue( )
//processing all the neighbours of v
for all neighbours w of v in Graph G
if w is not visited
Q.enqueue( w ) //Stores w in Q to further visit its neighbour
mark w as visited.
75
Program:
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
};
/* function declarations */
/*global declarations */
int queue[20];
void main()
int num = 1;
while (1)
{
76
scanf("%d", &num);
if (num == 0)
break;
new = malloc(sizeof(node));
new->value = num;
if (root == NULL)
root = new;
else
insert(new, root);
queue[++rear] = root->value;
bfs_traverse(root);
printf("%d\n", root->right->right->right->value);
77
void insert(node * new , node *root)
if (new->value>root->value)
if (root->right == NULL)
root->right = new;
else
if (root->left == NULL)
root->left = new;
else
val = root->value;
78
if ((front <= rear)&&(root->value == queue[front]))
if (root->left != NULL)
queue[++rear] = root->left->value;
queue[++rear] = root->right->value;
front++;
if (root->left != NULL)
bfs_traverse(root->left);
if (root->right != NULL)
bfs_traverse(root->right);
Output:
79
60
70
80
0
elements in a tree in inorder are
40 -> 20 -> 60 -> 10 -> 30 -> 70 -> 80
Viva Question:
1. Time Complexity of Breadth First Search is? (V – number of vertices, E – number of edges)
3. Breadth First Search is equivalent to which of the traversal in the Binary Trees?
80
Experiment No.: 11.2
Theory: The aim of DFS algorithm is to traverse the graph in such a way that it tries to go far from
the root node. Stack is used in the implementation of the depth first search.
Algorithm:
DFS(G, u)
u.visited = true
for each v in G.Adj[u]
if v.visited == false
DFS(G,v)
init() {
For each u in G
u.visited = false
For each u in G
DFS(G, u)
}
81
Program:
#include<stdio.h>
#include<stdlib.h>
int vertex;
}node;
node *G[20];
int visited[20];
int n;
void read_graph();
void insert(int,int);
void DFS(int);
void main()
int i;
read_graph();
//initialised visited to 0
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
82
}
void DFS(int i)
node *p;
printf("\n%d",i);
p=G[i];
visited[i]=1;
while(p!=NULL)
i=p->vertex;
if(!visited[i])
DFS(i);
p=p->next;
void read_graph()
int i,vi,vj,no_of_edges;
scanf("%d",&n);
for(i=0;i<n;i++)
{
83
G[i]=NULL;
scanf("%d",&no_of_edges);
for(i=0;i<no_of_edges;i++)
printf("Enter an edge(u,v):");
scanf("%d%d",&vi,&vj);
insert(vi,vj);
node *p,*q;
q=(node*)malloc(sizeof(node));
q->vertex=vj;
q->next=NULL;
if(G[vi]==NULL)
G[vi]=q;
else
{
84
//go to end of the linked list
p=G[vi];
while(p->next!=NULL)
p=p->next;
p->next=q;
Output:
Viva Questions:
1. Time Complexity of Depth First Search is? (V – number of vertices, E – number of edges)
Theory:
Given a connected and undirected graph, a spanning tree of that graph is a subgraph that is a tree and
connects all the vertices together. A single graph can have many different spanning trees. A minimum
spanning tree (MST) or minimum weight spanning tree for a weighted, connected and undirected
graph is a spanning tree with weight less than or equal to the weight of every other spanning tree. The
weight of a spanning tree is the sum of weights given to each edge of the spanning tree.
A minimum spanning tree has (V – 1) edges where V is the number of vertices in the given graph.
Algorithm:
Program:
#include<stdio.h>
#define MAX 30
int u,v,w;
}edge;
edge data[MAX];
int n;
}edgelist;
86
edgelist elist;
int G[MAX][MAX],n;
edgelist spanlist;
void kruskal();
void sort();
void print();
void main()
int i,j,total_cost;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
kruskal();
print();
void kruskal()
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;
87
for(i=1;i<n;i++){
for(j=0;j<i;j++)
if(G[i][j]!=0)
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j];
elist.n++;
sort();
for(i=0;i<n;i++)
belongs[i]=i;
spanlist.n=0;
for(i=0;i<elist.n;i++)
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);
if(cno1!=cno2)
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n=spanlist.n+1;
88
union1(belongs,cno1,cno2);
return(belongs[vertexno]);
int i;
for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
void sort()
int i,j;
edge temp;
for(i=1;i<elist.n;i++){
for(j=0;j<elist.n-1;j++){
if(elist.data[j].w>elist.data[j+1].w)
89
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
void print()
int i,cost=0;
for(i=0;i<spanlist.n;i++)
cost=cost+spanlist.data[i].w;
Output:
03200
30174
21050
07506
04060
Cost of the spanning tree=12
90