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

Lab Manual DS StudentFile

The document provides details about implementing various sorting algorithms in C like bubble sort, selection sort, insertion sort, and merge sort. It includes the theory, algorithms, programs and sample outputs for each sorting technique. It also lists some viva voice questions to evaluate the understanding of these sorting algorithms. The objective is to learn and implement fundamental data structures and algorithms concepts in C programming language.

Uploaded by

Lio
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)
92 views

Lab Manual DS StudentFile

The document provides details about implementing various sorting algorithms in C like bubble sort, selection sort, insertion sort, and merge sort. It includes the theory, algorithms, programs and sample outputs for each sorting technique. It also lists some viva voice questions to evaluate the understanding of these sorting algorithms. The objective is to learn and implement fundamental data structures and algorithms concepts in C programming language.

Uploaded by

Lio
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/ 90

DATA

STRUCTURE_USING C
LAB MANUAL
KCS – 351

Prepared by
Dr. Paramita De

Department of Information Technology


G L Bajaj Institute of Technology And Management
Greater Noida- 201306

1
List of Experiments
Minimum Ten / Eight experiments to be performed (As per syllabi)

S. No. List of Experiments


1. Sorting Algorithms-Non-Recursive.
2. Sorting Algorithms-Recursive.
3. Searching Algorithm.
4. To implement Stack using array.
5. To implement Queue using array.
6. To implement circular queue using array.
7. To implement stack using linked list.
8. To implement queue using linked list.
9. To implement circular queue using linked list.
10. Implementation of Tree Structures, Binary Tree, Tree Traversal,
Binary Search Tree, Insertion and Deletion in BST.
11. Graph Implementation, BFS, DFS, Minimum cost spanning tree,
shortest path algorithm.

Experiment No.: 1.1

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)

for all elements of list


if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for

return list

end BubbleSort

Program:

#include<stdio.h>

void Bubble_sort(int a[], int max)

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;

void display(int a[],int max)

int i;

printf("\n The sorted array is:\n");

for(i=0;i<max;i++)

printf("%d ",a[i]);

main()

int i,ch,yn,max;

int a[10];

printf("Enter the size of the array:");

scanf("%d",&max);

printf("\nEnter the elements:\n");

for(i=0;i<max;i++)

scanf("%d",&a[i]);

Bubble_sort(a,max);
4
display(a,max);

Output:

Enter the size of the array 5

Enter the elements:

The sorted array is:

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?

2. What is the best time complexity of bubble sort?

3. What is the maximum number of comparisons if there are 5 elements in array x?

4. In a bubble sort structure, there is/are?

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.

Experiment No.: 1.2


5
Objective : - Implement Selection Sort.

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:

procedure selection sort


list : array of items
n : size of list

for i = 1 to n - 1
/* set current element as minimum*/
min = i

/* check the element to be minimum */

for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for

/* swap the minimum element with the current element*/


if indexMin != i then
swap list[min] and list[i]
end if
end for
6
end procedure

Program:

#include<stdio.h>

int min(int a[], int j, int n)

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);

void select(int a[],int n)

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;

printf("\n The sorted array\n");

for(j=0;j<n;j++)

printf("%d ",a[j]);

void main()

int a[10],n,i;

printf("Enter the range");

scanf("%d",&n);

printf("\n Enter the elements");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

select(a,n);

Output:
8
Enter the size of the array 5

Enter the elements:

The sorted array is:

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?

2. What is the worst case complexity for selection sort algorithm?

3. In a selectionsort of n elements, how many times is the swap function called in the complete
execution of the algorithm?

4. What is sorting technique of selection sort?

5. What is the best case complexity for selection sort algorithm?

Experiment No.: 1.3


9
Objective : - Implement Insertion Sort.

Theory:

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is


always sorted. For example, the lower part of an array is maintained to be sorted. An element which
is to be inserted in this sorted sub-list, has to find its appropriate place and then it has to be inserted
there. Hence the name, insertion sort.

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:

procedure insertionSort( A : array of items )


int holePosition
int valueToInsert
for i = 1 to length(A) inclusive do:

/* select value to be inserted */


valueToInsert = A[i]
holePosition = i

/*locate hole position for the element to be inserted */

while holePosition > 0 and A[holePosition-1] > valueToInsert do:


A[holePosition] = A[holePosition-1]
holePosition = holePosition -1
end while

/* insert the number at hole position */


A[holePosition] = valueToInsert

end for

end procedure

Program:
10
#include<stdio.h>

void Insertion_sort(int a[], int max)

int i,j,t;

for(i=1;i<max;i++){

t=a[i];

for(j=i-1 ;j>=0 && t<a[j];j--){

a[j+1]=a[j];

a[j+1]=t;

void display(int a[],int max)

int i;

printf("\n The sorted array is:\n");

for(i=0;i<max;i++)

printf("%d ",a[i]);

main()

int i,ch,yn,max;

int a[10];

printf("Enter the size of the array:");

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:

Enter the size of the array 5

Enter the elements:

The sorted array is:

13479

Viva Questions:

1. What is the total number of comparisons for insertion sort?

2. In which cases are the time complexities same in insertion sort?

3. Insertion sort is in-place or out-place sorting?

4. Give an real example of insertion sort.

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?

Experiment No.: 2.1

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>

void Merge(int a[],int low,int mid,int high)

int i,j,k,h;

int b[10];

i=low;h=low;j=mid+1;

while(h<=mid && j <=high){

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];

void Merge_sort(int a[],int l,int h)

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);

//-------------- Display -----------------------------//

void display(int a[],int max)

int i;

printf("\n The sorted array is:\n");

for(i=0;i<max;i++)

printf("%d ",a[i]);
15
}

main()

int i,ch,yn,max;

int a[10];

printf("Enter the size of the array:");

scanf("%d",&max);

printf("\nEnter the elements:\n");

for(i=0;i<max;i++)

scanf("%d",&a[i]);

Merge_sort(a,0,max-1);

display(a,max);

Output:

Enter the size of the array 5

Enter the elements:

The sorted array is:

13479

16
Viva Questions:

1. Which strategy is used in Merge sort?

2. What is the average case complexity for merge sort algorithm?

3. What is the worst case complexity for merge sort algorithm?

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?

Experiment No.: 2.2


17
Objective : - Implement Quick Sort.

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:

Quick_Sort(A[], beg, end)

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:

//------------------- Quick Sort -------------------------------//

int partition(int a[],int m,int n)

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;

void Quick_sort(int a[],int p,int q)

int i,j,t;

if(p<=q){

j=partition(a,p,q);

Quick_sort(a,p,j-1);

Quick_sort(a,j+1,q);

//-------------- Display -----------------------------//

void display(int a[],int max)

int i;

printf("\n The sorted array is:\n");

for(i=0;i<max;i++)

printf("%d ",a[i]);

main()

int i,ch,yn,max;

int a[10];

printf("Enter the size of the array:");


20
scanf("%d",&max);

printf("\nEnter the elements:\n");

for(i=0;i<max;i++)

scanf("%d",&a[i]);

Quick_sort(a,0,max-1);

display(a,max);

Output:

Enter the size of the array 5

Enter the elements:

The sorted array is:

13479

Viva Questions:

1. Which strategy is used in Quick sort?

2. What is the average case complexity for quick sort algorithm?

3. What is the worst case complexity for quick sort algorithm?

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

Objective : - Implement Linear Search.

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:

Linear Search ( Array A, Value x)

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

procedure linear_search (list, value)

for each item in the list


if match item == value
return the item's location
end if
end for

end procedure

22
Program:

#include<stdio.h>

//#define max 5

//int a[max];

void Linear_search(int a[],int max,int t)

int i,l,flag=0;

for(i=0;i<max;i++){

if(a[i]==t){

flag=1;

break;

if(flag==1)

printf("\n %d is present in location %d",t,i+1);

else

printf("\n Not present");

main()

int i,max,a[10],t;

printf("\nEnter the size of the array");

scanf("%d",&max);

printf("\nEnter the array elements:\n");

for(i=0;i<max;i++)
23
scanf("%d",&a[i]);

printf("\n Enter the target element:");

scanf("%d",&t);

Linear_search(a,max,t);

Output:

Enter the size of the array 5

Enter the array elements:

Enter the target elements: 6

6 is present in location 4

Viva Questions:

1. Where is linear searching used?

2. What is the best case for linear search?

3. What is the worst case for linear search?

4. What is the disadvantage of linear search?

24
Experiment No.: 3.2

Objective : - Implement Binary Search.

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

1. Set BEG = lower_bound


END = upper_bound, POS = - 1

2. Repeat Steps 3 and 4 while BEG <=END

3. Set MID = (BEG + END)/2

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];

void Binary_search(int a[],int max,int t)

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)

printf("\n target %d is present in location %d",t,loc);

else

printf("\n target not found");

int R_Binary_search(int a[],int l,int h,int t)

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{

printf("\n Press 1. Binary Search 2. Recursive Binary Search\n");

printf("\n Enter your choice\n");

scanf("%d",&ch);

printf("\nEnter the size of the array");

scanf("%d",&max);

printf("\nEnter the array elements:\n");

for(i=0;i<max;i++)

scanf("%d",&a[i]);

printf("\n Enter the target element:");

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)

printf("\n Not found");

else

printf("\n Found in %d",m+1);

printf("\nwant to continue\n");
28
scanf("%d",&yn);

}while(yn==1);

Output:

Press 1. Binary Search 2. Recursive Binary Search

Enter your choice 1

Enter the size of the array 5

Enter the array elements:

11

222

Enter the target elements: 5

target 11 is present in location 2

Viva Questions:

1. What is the worst case complexity of binary search using recursion?

2. What are the applications of binary search?

3. Binary Search follow which strategy?

4. What is the advantage of recursive approach than an iterative approach?

5. What is the time complexity of binary search with iteration?

29
Experiment No.: 4

Objective : - Implement stack using array.

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.

1. If (TOP == MAX-1) Then

2. Print: Overflow [Check for overflow]

3. Else

4. Set TOP = TOP + 1 [Increment TOP by 1]

5. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK]

6. Print: ITEM inserted

[End of If]

7. Exit

Pop ( ):

Description: Here STACK is an array with MAX locations. TOP points to the top most element.

1. If (TOP == -1) Then [Check for underflow]

2. Print: Underflow

3. Else

4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM]

5. Set TOP = TOP - 1 [Decrement TOP by 1]

6. Print: ITEM deleted

30
[End of If]

7. Exit

Program:
#include<stdio.h>

#define max 5

int top=-1;

void push(int s[],int item)

if(top==max-1)

printf("Stack full");

else{

top=top+1;

s[top]=item;

int pop(int s[])

int item;

if(top==-1){

printf("Stack empty");

return -1;

else{

item=s[top];
31
top=top-1;

return item;

void display(int s[])

int i;

printf("\n The stack is:\n");

for(i=top;i>=0;i--)

printf("\n%d",s[i]);

main()

int ch,st[max],item,yn;

while(1){

printf("Press 1. Push 2. Pop 3. Display\n");

printf("Enter your choice");

scanf("%d", & ch);

switch(ch){

case 1: printf("\n Enter the item you want to insert:\n");

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;

printf("\n Do you want to continue: (0/1)\n");

scanf("%d",&yn);

if(yn==0)

break;

Output:

Press 1. Push 2. Pop 3. Display

Enter your choice 1

Enter the item you want to insert: 1

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice1

Enter the item you want to insert: 2

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice 1

Enter the item you want to insert: 3

Do you want to continue: (0/1) 1


33
Press 1. Push 2. Pop 3. Display

Enter your choice 3

The stack is:

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice 2

The deleted item is: 3

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice 3

The stack is:

Do you want to continue: (0/1) 0

Viva Questions:

1. What is a stack?

2. What are the application area of stack?

3. What do you understand by stack overflow and underflow?

4. Differentiate between array and stack.

5. Differentiate between peek and pop function.

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:

Input : An element say ITEM that has to be inserted.


Output : ITEM is at the REAR of the Queue.
Data structure : Que is an array representation of queue structure with two pointer FRONT and
REAR.

Steps:

1. If ( REAR = size ) then //Queue is full


2. print "Queue is full"
3. Exit
4. Else
5. If ( FRONT = 0 ) and ( REAR = 0 ) then //Queue is empty
6. FRONT = 1
7. End if
8. REAR = REAR + 1 // increment REAR
9. Que[ REAR ] = ITEM
10. End if
11. Stop

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:

1.If ( FRONT = 0 ) then


2. print "Queue is empty"
3. Exit
4. Else
5. ITEM = Que [ FRONT ]
6. If ( FRONT = REAR )
7. REAR = 0
8. FRONT = 0
9. Else
10. FRONT = FRONT + 1
11. End if
12. End if
13. Stop

Program:

#include<stdio.h>

#define max 5

int front=-1;

int rear =-1;

int c=0;

void insert(int q[],int item)

if(rear==max-1)

printf("Queue full");

else{

36
if(c==0){

front=0;c++;

rear=rear+1;

q[rear]=item;

int delete(int q[])

int item;

if(front==-1){

printf("Queue empty");

return -1;

else{

item=q[front];

front=front+1;

return item;

void display(int q[])

int i;

printf("\n The queue is:\n");


37
for(i=front;i<=rear;i++)

printf(" %d",q[i]);

main()

int ch,q[max],item,yn;

while(1){

printf("Press 1. Insert 2. Delete 3. Display\n");

printf("Enter your choice");

scanf("%d", & ch);

switch(ch){

case 1: printf("\n Enter the item you want to insert:\n");

scanf("%d",&item);

insert(q,item);

break;

case 2: item=delete(q);

if(item>-1)

printf("\n The deleted item is: %d\n",item);

break;

case 3: display(q);

break;

printf("\n Do you want to continue: (0/1)\n");

scanf("%d",&yn);
38
if(yn==0)

break;

Output:

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert: 1

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert: 2

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert: 3

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 3

The queue is:

1 2 3

Do you want to continue: (0/1)

Press 1. Insert 2. Delete 3. Display


39
Enter your choice 2

The deleted item is: 1

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 3

The queue is:

2 3

Do you want to continue: (0/1) 0

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

Objective : - Implement circular queue using array.

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:

enQueue(value) - Inserting value into the Circular Queue


In a circular queue, enQueue() is a function which is used to insert an element into the circular
queue. In a circular queue, the new element is always inserted at rear position. The enQueue()
function takes one integer value as parameter and inserts that value into the circular queue. We can
use the following steps to insert an element into the circular queue.
 Step 1: Check whether queue is FULL. ((rear == SIZE-1 && front == 0) || (front ==
rear+1))
 Step 2: If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and
terminate the function.
 Step 3: If it is NOT FULL, then check rear == SIZE - 1 && front != 0 if it is TRUE, then
set rear = -1.
 Step 4: Increment rear value by one (rear++), set queue[rear] = value and check 'front ==
-1' if it is TRUE, then set front = 0.

deQueue() - Deleting a value from the Circular Queue


In a circular queue, deQueue() is a function used to delete an element from the circular queue. In a
circular queue, the element is always deleted from front position. The deQueue() function doesn't
take any value as parameter. We can use the following steps to delete an element from the circular
queue...
 Step 1: Check whether queue is EMPTY. (front == -1 && rear == -1)
 Step 2: If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!"
and terminate the function.
 Step 3: If it is NOT EMPTY, then display queue[front] as deleted element and increment
the front value by one (front ++). Then check whether front == SIZE, if it is TRUE, then
set front = 0. Then check whether both front - 1 and rear are equal (front -1 == rear), if it
TRUE, then set both front and rear to '-1' (front = rear = -1).
41
display() - Displays the elements of a Circular Queue
We can use the following steps to display the elements of a circular queue...
 Step 1: Check whether queue is EMPTY. (front == -1)
 Step 2: If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function.
 Step 3: If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front'.
 Step 4: Check whether 'front <= rear', if it is TRUE, then display 'queue[i]' value and
increment 'i' value by one (i++). Repeat the same until 'i <= rear' becomes FALSE.
 Step 5: If 'front <= rear' is FALSE, then display 'queue[i]' value and increment 'i' value by
one (i++). Repeat the same until'i <= SIZE - 1' becomes FALSE.
 Step 6: Set i to 0.
 Step 7: Again display 'cQueue[i]' value and increment i value by one (i++). Repeat the same
until 'i <= rear' becomes FALSE.

Program:

#include<stdio.h>

#define max 3

int front=-1;

int rear =-1;

int c=0;

void insert(int q[],int item)

if((rear==max-1 && front ==0) || (rear==front-1))

printf("Queue full");

else if(rear==-1 && front==-1)

front=0;

rear=0;

q[rear]=item;
42
}

else if(rear==max-1 && front!=0){

rear=0;

q[rear]=item;

else{

rear=rear+1;

q[rear]=item;

int delete(int q[])

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;

void display(int q[])

int i;

printf("\n The queue is:\n");

for(i=0;i<max;i++)

printf(" %d",q[i]);

main()

int ch,q[max],item,yn;

while(1){

printf("Press 1. Insert 2. Delete 3. Display\n");

printf("Enter your choice");

scanf("%d", & ch);

switch(ch){

case 1: printf("\n Enter the item you want to insert:\n");

scanf("%d",&item);
44
insert(q,item);

break;

case 2: item=delete(q);

if(item>-1)

printf("\n The deleted item is: %d\n",item);

break;

case 3: display(q);

break;

printf("\n Do you want to continue: (0/1)\n");

scanf("%d",&yn);

if(yn==0)

break;

Output:

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert:1

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert: 2

Do you want to continue: (0/1) 1


45
Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert:3

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert:4

Queue full

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 3

The queue is:

1 2 3

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 2

The deleted item is: 1

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 3

The queue is:

0 2 3

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 1


46
Enter the item you want to insert:4

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 3

The queue is:

4 2 3

Do you want to continue: (0/1) 0

Viva Questions:

1. What is the overflow condition of circular queue?

2. What is circular queue?

3. How circular queue are better than linear queue?

47
Experiment No.: 7

Objective : - Implement stack using linked list.

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:

push(value) - Inserting an element into the Stack


Use the following steps to insert a new node into the stack...
 Step 1: Create a newNode with given value.
 Step 2: Check whether stack is Empty (top == NULL)
 Step 3: If it is Empty, then set newNode → next = NULL.
 Step 4: If it is Not Empty, then set newNode → next = top.
 Step 5: Finally, set top = newNode.

pop() - Deleting an Element from a Stack


Use the following steps to delete a node from the stack...
 Step 1: Check whether stack is Empty (top == NULL).
 Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and
terminate the function
 Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
 Step 4: Then set 'top = top → next'.

48
 Step 7: Finally, delete 'temp' (free(temp)).

display() - Displaying stack of elements

Use the following steps to display the elements (nodes) of a stack...

 Step 1: Check whether stack is Empty (top == NULL).


 Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
 Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
 Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until
temp reaches to the first node in the stack (temp → next != NULL).
 Step 4: Finally! Display 'temp → data ---> NULL'

Program:

#include<stdio.h>

#include<stdlib.h>

struct node

int info;

struct node *next;

};

struct node *top=NULL;

struct node *ptr;

void push(int item)

ptr=(struct node*)malloc(sizeof(struct node));

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){

printf("Press 1. Push 2. Pop 3. Display\n");

printf("Enter your choice");

scanf("%d",&ch);

switch(ch){

case 1: printf("\n Enter the item you want to insert:\n");

scanf("%d",&item);

push(item);

break;

case 2: item=pop();

if(item>-1)

printf("\n The deleted item is: %d\n",item);

break;

case 3: display();
51
break;

printf("\n Do you want to continue: (0/1)\n");

scanf("%d",&yn);

if(yn==0)

break;

Output:

Press 1. Push 2. Pop 3. Display

Enter your choice 1

Enter the item you want to insert: 1

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice1

Enter the item you want to insert: 2

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice 1

Enter the item you want to insert: 3

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice 3

The stack is:


52
3

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice 2

The deleted item is: 3

Do you want to continue: (0/1) 1

Press 1. Push 2. Pop 3. Display

Enter your choice 3

The stack is:

Do you want to continue: (0/1) 0

Viva Questions:

1. What is a Linked list?

2. How many pointers are required to implement a simple Linked list?

3. How to represent a linked list node?

4. How many types of Linked lists are there?

5. Describe the steps to insert data at the starting of a singly list.

53
Experiment No.: 8

Objective : - Implement queue using linked list.

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:

enQueue(value) - Inserting an element into the Queue


Use the following steps to insert a new node into the queue...
 Step 1: Create a newNode with given value and set 'newNode → next' to NULL.
 Step 2: Check whether queue is Empty (rear == NULL)
 Step 3: If it is Empty then, set front = newNode and rear = newNode.
 Step 4: If it is Not Empty then, set rear → next = newNode and rear = newNode.

deQueue() - Deleting an Element from Queue


Use the following steps to delete a node from the queue...
 Step 1: Check whether queue is Empty (front == NULL).
 Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and
terminate from the function
 Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
 Step 4: Then set 'front = front → next' and delete 'temp' (free(temp)).

display() - Displaying the elements of Queue


Use the following steps to display the elements (nodes) of a queue...

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;

struct node *next;

};

struct node *front=NULL;

struct node *rear=NULL;

struct node *ptr;

void insert(int item)

ptr=(struct node*)malloc(sizeof(struct node));

ptr->info=item;

if(front==NULL && rear==NULL){

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;

printf("\n The queue is:\n");


56
ptr=front;

while(ptr!=rear->next){

printf(" %d",ptr->info);

ptr=ptr->next;

main()

int ch,item,yn;

while(1){

printf("Press 1. Insert 2. Delete 3. Display\n");

printf("Enter your choice");

scanf("%d", & ch);

switch(ch){

case 1: printf("\n Enter the item you want to insert:\n");

scanf("%d",&item);

insert(item);

break;

case 2: item=delete();

if(item>-1)

printf("\n The deleted item is: %d\n",item);

break;

case 3: display();
57
break;

printf("\n Do you want to continue: (0/1)\n");

scanf("%d",&yn);

if(yn==0)

break;

Output:

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert: 1

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert: 2

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 1

Enter the item you want to insert: 3

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 3

58
The queue is:

1 2 3

Do you want to continue: (0/1)

Press 1. Insert 2. Delete 3. Display

Enter your choice 2

The deleted item is: 1

Do you want to continue: (0/1) 1

Press 1. Insert 2. Delete 3. Display

Enter your choice 3

The queue is:

2 3

Do you want to continue: (0/1) 0

Viva Questions:

1. How to insert a node at the end of Linked list?

2. How to insert a node in random location in the list?

3. How to delete a node from linked list?

4. How to reverse a singly linked list?

5. What are the advantages of Linked lists over Arrays?

59
Experiment No.: 9

Objective : - Implement circular queue using linked list.

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:

1. Create a new node dynamically and insert value into it.


2. Check if front==NULL, if it is true then front = rear = (newly created node)
3. If it is false then rare=(newly created node) and rear node always contains the address of the
front node.

 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:

1. Check whether queue is empty or not means front == NULL.


2. If it is empty then display Queue is empty. If queue is not empty then step 3
3. Check if (front==rear) if it is true then set front = rear = NULL else move the front forward
in queue, update address of front in rear node and return the element

Program:

struct Node
{
int data;
struct Node* link;
};

struct Queue
{
struct Node *front, *rear;
};

// Function to create Circular queue


void enQueue(Queue *q, int value)
60
{
struct Node *temp = new Node;
temp->data = value;
if (q->front == NULL)
q->front = temp;
else
q->rear->link = temp;

q->rear = temp;
q->rear->link = q->front;
}

// Function to delete element from Circular Queue


int deQueue(Queue *q)
{
if (q->front == NULL)
{
printf ("Queue is empty");
return INT_MIN;
}

// If this is the last node to be deleted


int value; // Value to be dequeued
if (q->front == q->rear)
{
value = q->front->data;
free(q->front);
q->front = NULL;
q->rear = NULL;
}
else // There are more than one nodes
{
struct Node *temp = q->front;
value = temp->data;
q->front = q->front->link;
q->rear->link= q->front;
free(temp);
}

return value ;
}

// Function displaying the elements of Circular Queue


void displayQueue(struct Queue *q)
{
struct Node *temp = q->front;

61
printf("\nElements in Circular Queue are: ");
while (temp->link != q->front)
{
printf("%d ", temp->data);
temp = temp->link;
}
printf("%d", temp->data);
}

/* Driver of the program */


int main()
{
// Create a queue and initialize front and rear
Queue *q = new Queue;
q->front = q->rear = NULL;

// Inserting elements in Circular Queue


enQueue(q, 14);
enQueue(q, 22);
enQueue(q, 6);

// Display elements present in Circular Queue


displayQueue(q);

// Deleting elements from Circular Queue


printf("\nDeleted value = %d", deQueue(q));
printf("\nDeleted value = %d", deQueue(q));

// Remaining elements in Circular Queue


displayQueue(q);

enQueue(q, 9);
enQueue(q, 20);
displayQueue(q);

return 0;
}

Output:

Elements in Circular Queue are: 14 22 6


Deleted value = 14
Deleted value = 22
Elements in Circular Queue are: 6
Elements in Circular Queue are: 6 9 20

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:

struct node *node add_new_node (struct node *node, int value)


{
if (node == NULL) {
node=add_new_node(value);
return node;
}
else if (value = node->value){
return NULL;
}
else if (value < node -> value){
if(node->left==NULL)
node->left = add_new_node(value);
else
add_new_node(node->left,value);
}
else if(value>node->value){
if(node->right==NULL)
node->right=add_new_node(value);
else
63
add_new_node(node->right,value);
}
}

Program:

#include<stdio.h>

#include<malloc.h>

typedef struct node

int data;

struct node *left;

struct node *right;

}node;

node *create()

node *p;

int x;

printf("Enter data(-1 for no data):");

scanf("%d",&x);

if(x==-1)

return NULL;

p=(node*)malloc(sizeof(node));

64
p->data=x;

printf("Enter left child of %d:\n",x);

p->left=create();

printf("Enter right child of %d:\n",x);

p->right=create();

return p;

void preorder(node *t) //address of root node is passed in t

if(t!=NULL)

printf("%d",t->data); //visit the root

preorder(t->left); //preorder traversal on left subtree

preorder(t->right); //preorder traversal om right subtree

int main()

node *root;

root=create();

printf("\nThe preorder traversal of tree is:\n");


65
preorder(root);

return 0;

Output:

Enter data(-1 for no data):3

Enter left child of 3:

Enter data(-1 for no data):4

Enter left child of 4:

Enter data(-1 for no data):1

Enter left child of 1:

Enter data(-1 for no data):-1

Enter right child of 1:

Enter data(-1 for no data):-1

Enter right child of 4:

Enter data(-1 for no data):7

Enter left child of 7:

Enter data(-1 for no data):-1

Enter right child of 7:

Enter data(-1 for no data):-1

Enter right child of 3:

Enter data(-1 for no data):5

Enter left child of 5:

Enter data(-1 for no data):2

Enter left child of 2:

Enter data(-1 for no data):-1


66
Enter right child of 2:

Enter data(-1 for no data):-1

Enter right child of 5:

Enter data(-1 for no data):8

Enter left child of 8:

Enter data(-1 for no data):-1

Enter right child of 8:

Enter data(-1 for no data):-1

The preorder traversal of tree is:

3417528

Viva Questions:

1. What is binary tree?

2. What are the two way to represent binary tree in memory?Which one do you prefer and why?

3. What is complete binary tree?

4. What is expression tree?

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:

struct node* search(int data){


struct node *current = root;
printf("Visiting elements: ");

while(current->data != data){

if(current != NULL) {
printf("%d ",current->data);

//go to left tree


if(current->data > data){
current = current->leftChild;
} //else go to right tree
else {
current = current->rightChild;
}

//not found
if(current == NULL){

68
return NULL;
}
}
}

return current;
}

void insert(int data) {


struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;

tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;

//if tree is empty


if(root == NULL) {
root = tempNode;
} else {
current = root;
parent = NULL;

while(1) {
parent = current;

//go to left of the tree


if(data < parent->data) {
current = current->leftChild;
//insert to the left

if(current == NULL) {
parent->leftChild = tempNode;
return;
}
} //go to right of the tree
else {

69
current = current->rightChild;

//insert to the right


if(current == NULL) {
parent->rightChild = tempNode;
return;
}
}
}
}
}

Program:

#include<stdio.h>

#include<stdlib.h>

struct node

int info;

struct node *left;

struct node *right;

};

struct node *start=NULL;

struct node *root=NULL;

struct node* create(struct node *root, int data)

if(root == NULL){

root=(struct node*)malloc(sizeof(struct node));

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

printf("\n duplicate data");

return root;

void inorder(struct node *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);

void postorder(struct node *root)

if(root!=NULL){

postorder(root->left);

postorder(root->right);

printf("%d ",root->info);

main()

int n,ch,i,d;

struct node* root=NULL;

do{

printf("\n 1. Create 2. Inorder 3. preorder 4. postorder 5. exit\n");

printf("Enter your choice:");

scanf("%d",&ch);

switch(ch)
72
{

case 1: root=NULL;

printf("\n enter no. of nodes");

scanf("%d",&n);

for(i=0;i<n;i++){

printf("\nEnter the data:\n");

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:

1. Create 2. Inorder 3. preorder 4. postorder 5. exit


73
Enter your choice:1

enter no. of nodes 7

Enter the data: 3

Enter the data: 4

Enter the data: 5

Enter the data: 1

Enter the data: 7

Enter the data: 2

Enter the data: 8

1. Create 2. Inorder 3. preorder 4. postorder 5. exit

Enter your choice:2

1234578

1. Create 2. Inorder 3. preorder 4. postorder 5. exit

Enter your choice:3

3124578

1. Create 2. Inorder 3. preorder 4. postorder 5. exit

Enter your choice:4

2187543

1. Create 2. Inorder 3. preorder 4. postorder 5. exit

Enter your choice:

Viva Questions:

1. How to search a key in binary search tree?

2. What is the speciality about the inorder traversal of a binary search tree?
74
Experiment No.: 11.1

Objective : - Implement BFS using linked list.

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 1: Push the root node in the Queue.

Step 2: Loop until the queue is empty.

Step 3: Remove the node from the Queue.

Step 4: If the removed node has unvisited child nodes, mark them as visited and insert the unvisited
children in the queue.

BFS (G, s) //Where G is the graph and s is the source node

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;

struct btnode *left, *right;

};

typedef struct btnode node;

/* function declarations */

void insert(node *, node *);

void bfs_traverse(node *);

/*global declarations */

node *root = NULL;

int val, front = 0, rear = -1, i;

int queue[20];

void main()

node *new = NULL ;

int num = 1;

printf("Enter the elements of the tree(enter 0 to exit)\n");

while (1)

{
76
scanf("%d", &num);

if (num == 0)

break;

new = malloc(sizeof(node));

new->left = new->right = NULL;

new->value = num;

if (root == NULL)

root = new;

else

insert(new, root);

printf("elements in a tree in inorder are\n");

queue[++rear] = root->value;

bfs_traverse(root);

for (i = 0;i <= rear;i++)

printf("%d -> ", queue[i]);

printf("%d\n", root->right->right->right->value);

/* inserting nodes of a tree */

77
void insert(node * new , node *root)

if (new->value>root->value)

if (root->right == NULL)

root->right = new;

else

insert (new, root->right);

if (new->value < root->value)

if (root->left == NULL)

root->left = new;

else

insert (new, root->left);

/* displaying elements using BFS traversal */

void bfs_traverse(node *root)

val = root->value;

78
if ((front <= rear)&&(root->value == queue[front]))

if (root->left != NULL)

queue[++rear] = root->left->value;

if (root->right != NULL || root->right == NULL)

queue[++rear] = root->right->value;

front++;

if (root->left != NULL)

bfs_traverse(root->left);

if (root->right != NULL)

bfs_traverse(root->right);

Output:

Enter the elements of the tree(enter 0 to exit)


40
20
10
30

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)

2. The Breadth First Search traversal of a graph will result into?

3. Breadth First Search is equivalent to which of the traversal in the Binary Trees?

4. Which Data structure is used in standard implementation of Breadth First Search ?

80
Experiment No.: 11.2

Objective : - Implement DFS using linked list.

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:

Step 1: Push the root node in the Stack.


Step 2: Loop until stack is empty.
Step 3: Peek the node of the stack.
Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it as traversed and
push it on stack.
Step 5: If the node does not have any unvisited child nodes, pop the node from the stack

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>

typedef struct node

struct node *next;

int vertex;

}node;

node *G[20];

//heads of linked list

int visited[20];

int n;

void read_graph();

//create adjacency list

void insert(int,int);

//insert an edge (vi,vj) in te adjacency list

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;

printf("Enter number of vertices:");

scanf("%d",&n);

//initialise G[] with a null

for(i=0;i<n;i++)

{
83
G[i]=NULL;

//read edges and insert them in G[]

printf("Enter number of edges:");

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);

void insert(int vi,int vj)

node *p,*q;

//acquire memory for the new node

q=(node*)malloc(sizeof(node));

q->vertex=vj;

q->next=NULL;

//insert the node in the linked list number vi

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:

Enter number of vertices:8


Enter number of edges:10
Enter an edge(u,v):0 1
Enter an edge(u,v):0 2
Enter an edge(u,v):0 3
Enter an edge(u,v):0 4
Enter an edge(u,v):1 5
Enter an edge(u,v):2 5
Enter an edge(u,v):3 6
Enter an edge(u,v):4 6
Enter an edge(u,v):5 7
Enter an edge(u,v):6 7
0
1
5
7
2
3
6
4

Viva Questions:

1. Time Complexity of Depth First Search is? (V – number of vertices, E – number of edges)

2. Which Data structure is used in standard implementation of Breadth First Search ?


85
Experiment No.: 11.3

Objective : - Implement Kruskal’s algorithm.

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:

1. Sort all the edges in non-decreasing order of their weight.


2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not
formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.

Program:

//========== Kruskal's Algorithm =================//

#include<stdio.h>

#define MAX 30

typedef struct edge

int u,v,w;

}edge;

typedef struct edgelist

edge data[MAX];

int n;

}edgelist;

86
edgelist elist;

int G[MAX][MAX],n;

edgelist spanlist;

void kruskal();

int find(int belongs[],int vertexno);

void union1(int belongs[],int c1,int c2);

void sort();

void print();

void main()

int i,j,total_cost;

printf("\nEnter number of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\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);

int find(int belongs[],int vertexno)

return(belongs[vertexno]);

void union1(int belongs[],int c1,int c2)

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;

printf("\n\nCost of the spanning tree=%d",cost);

Output:

Enter the number of vertices:5

Enter the adjacency matrix:

03200
30174
21050
07506
04060
Cost of the spanning tree=12

90

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy