0% found this document useful (0 votes)
17 views62 pages

DS Lab Manual

The document outlines the vision and mission of the Master of Computer Applications (MCA) department, emphasizing the goal of producing competent engineers and managers. It includes Program Educational Objectives (PEOs) and Program Outcomes (POs) that detail the skills and knowledge students are expected to acquire. Additionally, it provides a list of tasks for a Data Structures Lab, including various programming assignments related to data structures and algorithms.

Uploaded by

Samuel Johnpeter
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)
17 views62 pages

DS Lab Manual

The document outlines the vision and mission of the Master of Computer Applications (MCA) department, emphasizing the goal of producing competent engineers and managers. It includes Program Educational Objectives (PEOs) and Program Outcomes (POs) that detail the skills and knowledge students are expected to acquire. Additionally, it provides a list of tasks for a Data Structures Lab, including various programming assignments related to data structures and algorithms.

Uploaded by

Samuel Johnpeter
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/ 62

DEPARTMENT OF

MASTER OF COMPUTER APPLICATIONS

DATA STRUCTURES LAB

Name

Roll Number

Year & Semester I Year I Semester

Regulation NECR MCA24

Branch MCA

Section
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

VISION OF INSTITUTION

To be one of the nation’s premier Institutions for Technical and Management Education and
a key contributor for Technological and Socio-economic Development of the Nation.
MISSION OF INSTITUTION
Requirements & actions are identified to achieve the vision
M To produce technically competent Engineers and Managers by maintaining high
1 academic standards, world class infrastructure and core instructions.
M To enhance innovative skills and multidisciplinary approach of students through well
2 experienced faculty and industry interactions.
To inculcate global perspective and attitude of students to face real world
M
challenges by developing leadership qualities, lifelong learning abilities and ethical
3
values.

VISION OF DEPARTMENT
To be recognized as a centre of excellence in imparting quality technical education to succeed in
the field of Computer Applications and to develop our students as professionals in upcoming
technologies with right knowledge, skills and attitude to meet the global needs/challenges of the
ever changing IT industry.
MISSION OF DEPARTMENT
To achieve professional excellence through learning practices in an environment which is congenial
for technical education and there by develop competitive professionals with proper leadership,
commitment and moral values.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


Program Educational Objectives (PEOs) of the department of MCA are listed below

PEO Outrival in professional carrier and/or higher education by acquiring


1 knowledge in mathematical, computing and engineering principles.
Achieve peer-recognition; as an individual or in a team; through professional
PEO
2 responsibilities to induce team spirit leadership quality to serve society &
industry.
PEO To prepare the graduates to adapt themselves for lifelong learning through
3 professional activities on latest technology and trends needed for a successful
career
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS

PROGRAM OUTCOMEs (POs)


Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO 1 fundamentals, and an engineering specialization to the solution of complex engineering
problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO 2 engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems
PO 3 and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and
PO 4 research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
PO 5 modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to
PO 6 assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
PO 7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
PO 8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO 9 Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
PO 10 engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the
PO 11 engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to
PO 12 engage in independent and life-long learning in the broadest context of technological
change.
PROGRAM SPECIFIC OUTCOMEs (PSOs)

PSO 1 Domain Specific Knowledge: Apply the techniques to develop solutions in the domains
of algorithms, computer programming, multimedia, web, data and networking.

PSO 2 Software Product Development: Apply the design and deployment principles to deliver
a quality application for various heterogeneous domains.
DATA STRUCTURES LAB
LIST OF TASKS
TASK-1
1. Write a Program to Implement the following Searching Algorithms:
a) Linear Search b) Binary Search

TASK-2
1. Implement the following using arrays:
A. Write a Program to Implement Stack Operations
B. Write a Program to convert a given infix expression into its Postfix using stack.
C. Write a Program to evaluate the Postfix Expression using stack
TASK-3
1. Write a Program to Implement Queue Operations using Arrays
2. Write a Program to Implement Circular Queue Operations using Arrays

TASK-4
1. Write a Program to implement the operations of Singly Linked List
2. Write a Program to implement the operations of Doubly Linked List

TASK-5
1. Write a Program to implement stack operations using linked list
2. Write a Program to implement the operations of Circular Singly Linked List

TASK-6
1. Write a Program to Sort the set of
elements:
a) Insertion Sortb) Quick Sort
TASK-7
1. Write a Program to Sort the set of elements:
a) Merge Sort b) Heap Sort
TASK-8
1. Write a Program to implement the following on trees
a) Insertion and deletion operations
b) Traversals
2. Write a Program to implement Binary Search Tree Operations.
TASK-9
1. Write a Program to implement the following Graph Traversal Algorithms:
a) Depth first traversal b) Breadth first traversal
TASK-10
1. Write a Program to implement the following Minimum Spanning Tree Algorithms:
a) Kruskal’s Algorithm b) Prim’s Algorithm
INDEX
PAGE
S.NO DATE NAME OF THE TASK SIGN.
NO.
PAGE
S.NO DATE NAME OF THE TASK SIGN.
NO.
TASK -1 Date:

Problem Statement:
Write a Source Code to implement Linear or sequential Search on the elements of a given array.

Source Code:// Linear Search using Function

#include<stdio.h> #include<conio.h> void main()


{
int a[10],i,n,key,flag = 0,loction=0;
printf("enter how many elements to search(n<10) :"); scanf("%d",&n);
printf("enter the %d element : ",n); for (i=0;i<n; i++)
{
printf("\nenter a[%d] element : ",i);
scanf("%d",&a[i]);
}

printf("\nenter key element : "); scanf("%d",&key);


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

if(a[i] ==key)
{

flag=1; location=i;
}
}

if(flag==1)
{

printf(" enter %d found",location);


}

else
{

printf("element not found");


}

Output:
enter how many elements to search(n<10) :5
enter the 5 element :
enter a[0] element : 5
enter a[1] element : 4
enter a[2] element : 3
enter a[3] element : 2
enter a[4] element : 1
enter key element : 3 enter 2 found
Executed Output:
Problem Statement:
Write a Source Code to implement Binary Search on the elements of a given array.

Source Code: // Binary Search using Function

#include<stdio.h> #include<conio.h> int main()


{
int i, arr[10],search,first,last,middle;
printf("enter 10 elements (in ascending order) : ");
for(i=0;i<10;i++)
{

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

printf("\nenter element to be search : "); scanf("%d",&search);


first = 0; last=9;
middle=(first+last)/2; while(first <= last)
{
if(arr[middle]<search)
{

first = middle+1;
}

else if (arr[middle]==search)
{

printf("\nthe number,%d found at position %d",search,middle+1); break;


}
else
{

last = middle-1;
}

middle = (first + last)/2;


}

if (first>last)
{

printf("\nthe number %d is not found in given array",search);


}

getch(); return 0;
}
Output:
enter 10 elements (in ascending order) : 1 2 3 4 5 6 7 8 9 10
enter element to be search : 6
the number,6 found at position 6
Executed Output:
TASK - 2 Date:
Source Code Statement:
Write a Source Code to implement operations on Stack using arrays.

Source Code: // operations on stack using arrays

#include<stdio.h>
int stack[100],choice,n,top,x,i; void push(void);
void pop(void); void display(void); int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:"); scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t ");
printf("\n\t 1.PUSH\n\t 2.POP\n\tDISPLAY\n\t 4.EXIT");
do
{

printf("\n Enter the Choice:"); scanf("%d",&choice); switch(choice)


{
case 1:
{

push(); break;
}
case 2:
{

pop(); break;
}
case 3:
{

display(); break;
}
case 4:
{

printf("\n\t EXIT POINT "); break;


}
default:
{

printf ("\n\t Please Enter


a Valid Choice(1/2/3/4)");
}

}
}

while(choice!=4); return 0;
}
void push()
{

if(top>=n-1)
{

printf("\n\tSTACK is over flow");


}

else
{

printf(" Enter a value to be pushed:"); scanf("%d",&x);


top++; stack[top]=x;
}
}

void pop()
{

if(top<=-1)
{

printf("\n\t Stack is under flow");


}

else
{

printf("\n\t The popped elements is %d",


stack[top]);
top--;
}

void display()
{

if(top>=0)
{

printf("\n The elements in STACK \n"); for(i=top; i>=0; i--)


printf("\n%d",stack[i]); printf("\n Press Next Choice");
}
else
{

printf("\n The STACK is empty");


}

Output:
Enter the size of STACK[MAX=100]:5
STACK OPERATIONS USING ARRAY

1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter the Choice:3 The STACK is empty Enter the Choice:1
Enter a value to be pushed:4
Enter the Choice:2
The popped elements is 4
Enter the Choice:5
Please Enter a Valid Choice(1/2/3/4)
Enter the Choice:4
EXIT POINT
Executed Output:
Problem Statement:
Write a Source Code to convert a given infix expression into its Postfix using stack.
Source Code: // Infix to Postfix Conversion
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1; else
return stack[top--];
}
int priority(char x)
{
if(x == '(') return 0;
if(x == '+' || x == '-') return 1;
if(x == '*' || x == '/') return 2;
return 0;
}

int main()
{
char exp[100]; char *e, x;
printf("Enter the expression : "); scanf("%s",exp);
printf("\n"); e = exp;
while(*e != '\0')
{
if(isalnum(*e)) printf("%c ",*e);
else if(*e == '(') push(*e);
else if(*e == ')')
{
while((x = pop()) != '(') printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e)) printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}
return 0;
}
Output:
Enter the expression: a+b-c a b + c -
Executed Output:
Problem Statement:
Write a Source Code to evaluate the Postfix Expression using stack

Source Code: // evaluation of the Postfix Expression using stack

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define SIZE 40 int pop();
void push(int);
char postfix[SIZE];
int stack[SIZE], top = -1; int main()
{
int i, a, b, result, pEval; char ch;
for(i=0; i<SIZE; i++)
{

stack[i] = -1;
}
printf("\nEnter a postfix expression: "); scanf("%s",postfix);
for(i=0; postfix[i] != '\0'; i++)
{

ch = postfix[i];
if(isdigit(ch))
{

push(ch-'0');
}

else if(ch == '+' || ch == '-' || ch == '*' || ch == '/')


{

b = pop();
a = pop();
switch(ch)
{

case '+': result = a+b;


break;
case '-': result = a-b;
break;
case '*': result = a*b;
break;
case '/': result = a/b;
break;
case '%':result = a%b; break;
}

push(result);
}

pEval = pop();
printf("\nThe postfix evaluation is: %d\n",pEval);
return 0;
}

void push(int n)
{

if (top < SIZE -1)


{

stack[++top] = n;
}

else
{
printf("Stack is full!\n"); exit(-1);

}}

int pop()
{

int n;
if (top > -1)
{

n = stack[top]; stack[top--] = -1; return n;

} { printf("Stack is empty!\n"); exit(-1);


}}
else
Output:
Enter a postfix expression: 456*+
The postfix evaluation is: 34
Executed Output:
TASK - 3 Date:

Source Code Statement :


Write a Source Code to implement operations on Queue using array
Source Code: // operations on Queue using array
#include<stdio.h> #define n 5
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n; printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit"); while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch); switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full"); else
{
printf("\n Enter no %d:",j++); scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]); x++;
}
break; case 3:
printf("\nQueue Elements are:\n "); if(front==rear)
printf("\n Queue is Empty"); else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]); printf("\n");
}
break; case 4:
printf("\n\t EXIT POINT"); break;
default:
printf("Wrong Choice: please see the options");
}
}
}
return 0;
}
Output:
Queue using Array 1.Insertion 2.Deletion 3.Display

4.Exit
Enter the Choice:1 Enter no 1:9
Enter the Choice:1 Enter no 2:8
Enter the Choice:1 Enter no 3:7
Enter the Choice:2 Deleted Element is 9 Enter the Choice:3 Queue Elements are: 8
7
Enter the Choice:4 EXIT POINT
Executed Output:
Problem Statement:
Write a Source Code to Implement Circular Queue Operations using Arrays.

Source Code: // Circular Queue Operations using Arrays


#include <stdio.h> #define SIZE 5
int items[SIZE];
int front = -1, rear = -1;
// Check if the queue is full int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1; return 0;
}
// Check if the queue is empty
int isEmpty() {
if (front == -1) return 1;
return 0;
}

// Adding an element
void enQueue(int element) { if (isFull())
printf("\n Queue is full!! \n"); else {
if (front == -1) front = 0; rear = (rear + 1) % SIZE; items[rear] = element;
printf("\n Inserted -> %d", element);
}}

// Removing an element int deQueue() {


int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n"); return (-1);
} else {
element = items[front]; if (front == rear) {
front = -1;
rear = -1;
}

// Q has only one element, so we reset the


// queue after dequeing it. ? else {
front = (front + 1) % SIZE;
}

printf("\n Deleted element -> %d \n", element); return (element);


}
}

// Display the queue


void display() {
int i;
if (isEmpty())
printf(" \n
Empty Queue\n"); else {
printf("\n Front -> %d ", front); printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) { printf("%d ", items[i]);
}
printf("%d ", items[i]); printf("\n Rear -> %d \n", rear);
}

int main() {
// Fails because front = -1 deQueue();
enQueue(1); enQueue(2); enQueue(3); enQueue(4); enQueue(5);
// Fails to enqueue because front == 0 && rear == SIZE - 1 enQueue(6);
display(); deQueue();
display();
enQueue(7); display();
// Fails to enqueue because front == rear + 1 enQueue(8);
return 0;
}

Output:
Queue is empty !!
Inserted -> 1
Inserted -> 2
Inserted -> 3
Inserted -> 4
Inserted -> 5 Queue is full!!
Front -> 0
Items -> 1 2 3 4 5
Rear -> 4

Deleted element -> 1 Front -> 1


Items -> 2 3 4 5

Rear -> 4
Inserted -> 7
Front -> 1
Items -> 2 3 4 5 7
Rear -> 0 Queue is full!!

Executed Output:
TASK - 4 Date:

Problem Statement:
Write a Source Code to implement operations on Singly linked list.

Source Code: // operations on Singly linked list


#include <stdio.h> #include <malloc.h> #include <stdlib.h> struct node {
int value;
struct node *next;
};

void insert();
void display();
void delete();
int count();

typedef struct node DATA_NODE;

DATA_NODE *head_node, *first_node, *temp_node = 0, *prev_node, next_node; int data;

int main() {
int option = 0;
printf("Singly Linked List Example - All Operations\n"); while (option < 5) {

printf("\nOptions\n");
printf("1 : Insert into Linked List \n"); printf("2 : Delete from Linked List \n"); printf("3 : Display
Linked List\n"); printf("4 : Count Linked List\n"); printf("Others : Exit()\n"); printf("Enter your
option:"); scanf("%d", &option);
switch (option) { case 1:
insert(); break; case 2: delete(); break; case 3: display(); break; case 4: count(); break; default: break;
}
}

return 0;
}

void insert() {
printf("\nEnter Element for Insert Linked List : \n"); scanf("%d", &data);
temp_node = (DATA_NODE *) malloc(sizeof (DATA_NODE)); temp_node->value = data;

if (first_node == 0) { first_node = temp_node;


} else {
head_node->next = temp_node;
}

temp_node->next = 0; head_node = temp_node; fflush(stdin);


}
void delete() {
int countvalue, pos, i = 0; countvalue = count(); temp_node = first_node;
printf("\nDisplay Linked List : \n");

printf("\nEnter Position for Delete Element : \n"); scanf("%d", &pos);

if (pos > 0 && pos <= countvalue) { if (pos == 1) {


temp_node = temp_node -> next; first_node = temp_node; printf("\nDeleted Successfully \n\n");
} else {
while (temp_node != 0) { if (i == (pos - 1)) {
prev_node->next = temp_node->next; if(i == (countvalue - 1))
{

head_node = prev_node;
}

printf("\nDeleted Successfully \n\n"); break;


} else { i++;
prev_node = temp_node; temp_node = temp_node -> next;
}
}
}

} else
printf("\nInvalid Position \n\n");
}

void display() { int count = 0;


temp_node = first_node; printf("\nDisplay Linked List : \n"); while (temp_node != 0) {
printf("# %d # ", temp_node->value); count++;
temp_node = temp_node -> next;
}

printf("\nNo Of Items In Linked List : %d\n", count);


}

int count() { int count = 0;


temp_node = first_node; while (temp_node != 0) { count++;
temp_node = temp_node -> next;
}

printf("\nNo Of Items In Linked List : %d\n", count); return count;


}

Output:
Singly Linked List Example - All Operations
Options
1 : Insert into Linked List
2 : Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others : Exit()
Enter your option:1
Enter Element for Insert Linked List : 2
Options
1 : Insert into Linked List
2 : Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others : Exit()
Enter your option:1
Enter Element for Insert Linked List : 3
Options
1 : Insert into Linked List
2 : Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others : Exit()
Enter your option:1
Enter Element for Insert Linked List : 4
Options
1 : Insert into Linked List
2 : Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others : Exit()
Enter your option:1
Enter Element for Insert Linked List : 5
Options
1 : Insert into Linked List
2 : Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others : Exit()
Enter your option:2
No Of Items In Linked List : 4 Display Linked List :

Enter Position for Delete Element : 2


Deleted Successfully
Options
1 : Insert into Linked List
2 : Delete from Linked List
3 : Display Linked List
4 : Count Linked List
Others : Exit()
Enter your option:3 Display Linked List :
#2 ##4 ##5 #
No Of Items In Linked List : 3
Options
1 : Insert into Linked List
2 : Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others : Exit()
Enter your option:4
No Of Items In Linked List : 3

Options
1 : Insert into Linked List
2 : Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others : Exit()
Enter your option:5
Executed Output:
Problem Statement:
Write a Source Code to implement the operations of Double Liked list

Source Code: //

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int count=0;
struct node
{
int data;
struct node *next,*prev;
}*head,*last,*newn,*trav;
//----------------------------------------------------
void create_list()
{
struct node *temp;
int value;
temp=last;
newn=(struct node *)malloc(sizeof (struct node));
printf("\n enter value");
scanf("%d",&value);
newn->data=value;
if(last==NULL)
{
head=last=newn;
head->prev=NULL;
head->next=NULL;
count++;
}
else
{
newn->next=NULL;
newn->prev=last;
last->next=newn;
last=newn;
count++;
}
}
//----------------------------------------------------
void insert_at_begning(int value)
{
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
if(head==NULL)
{
head=last=newn;
head->prev=NULL;
head->next=NULL;
count++;
}
else
{
newn->next=head;
head->prev=newn;
newn->prev=NULL;
head=newn;
count++;
}
}
//----------------------------------------------------------
void insert_at_end(int value)
{
struct node *temp;
temp=last;
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
if(last==NULL)
{
head=last=newn;
head->prev=NULL;
head->next=NULL;
count++;
}
else
{
newn->next=NULL;
newn->prev=last;
last->next=newn;
last=newn;
count++;
}
}
//------------------------------------------------------
int insert_at_middle()
{
if(count>=2)
{
struct node *var2,*temp;
int loc,value;
printf("\nselect location where you want to insert the data");
scanf("%d",&loc);
printf("\nenter which value do u want to inserted");
scanf("%d",&value);
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
temp=head;
while(temp->data!=loc)
{
temp=temp->next;
if(temp==NULL)
{
printf("\nSORRY...there is no %d element",loc);
return 0;
}
}
if(temp->next==NULL)
{
printf("\n%d is last node..please enter midddle node values ",loc) ;
return;
}
var2=temp->next;
temp->next=newn;
newn->next=var2;
newn->prev=temp;
var2->prev=newn;
count++;
}
else
{
printf("\nthe no of nodes must be >=2");
}
}
//----------------------------------------------------------------
int delete_from_middle()
{
if(count>2)
{
struct node *temp,*var;
int value;
temp=head;
printf("\nenter the data that you want to delete from the list shown above");
scanf("%d",&value);
while(temp!=NULL)
{
if(temp->data == value)
{
if(temp->next==NULL)//if(temp==head)
{
printf("\n\n sorry %d is last node ..please enter middle nodes only",value);
return 0;
}
else
{
if(temp==head)
{
printf("\n\n %d is first node..plz enter middle nodes",value);
return;

}
var->next=temp->next;
temp->next->prev=var;
free(temp);
count--;
return 0;
}
}
else
{
var=temp;
temp=temp->next;
}
}
if(temp==NULL)
printf("\n%d is not avilable.. enter only middle elements..",value);
else
printf("\ndata deleted from list is %d",value);
}
else
{
printf("\nthere no middle elemts..only %d elemts is avilable",count);
}
}
//------------------------------------------------------------------
int delete_from_front()
{
struct node *temp;
if(head==NULL)
{
printf("no elements for deletion in the list");
return 0;
}
else if(head->next==NULL)
{
printf("deleted element is :%d",head->data);
head=last=NULL;

}
else
{
temp=head->next;
printf("deleted element is :%d",head->data);
head->next=NULL;
temp->prev=NULL;
head=temp;
count--;
return 0;
}
}
//--------------------------------------------------------
int delete_from_end()
{
struct node *temp,*var;
temp=last;
if(last==NULL)
{
printf("no elemts in the list");
return 0;
}
else if(last->prev==NULL)
{
printf("data deleted from list is %d",last->data);
head=last=NULL;
//free(last);
count--;
return 0;
}
else{
printf("data deleted from list is %d",last->data);
var=last->prev;
last->prev->next=NULL;
last=var;
count--;
return 0;
}
}
//------------------------------------------------------
int display()
{
trav=last;//head;
if(trav==NULL)
{
printf("\nList is Empty");
return 0;
}
else
{
printf("\n\nElements in the List is %d:\n",count);
while(trav!=NULL)
{
printf("%d<--> ",trav->data);
trav=trav->prev;//next;
}
printf("\n");
}
}
//---------------------------------------------------------------
int main()
{
int ch=0;
char ch1;
// clrscr();
head=NULL;
last=NULL;
while(1)
{
Printf("\n Double Linked List Operations")
printf("\n1.Create Double Linked List");
printf("\n2.insertion at begning of linked list");
printf("\n3.insertion at the end of linked list");
printf("\n4.insertion at the middle where you want");
printf("\n5.deletion from the front of linked list");
printf("\n6.deletion from the end of linked list ");
printf("\n7.deletion of the middle data that you want");
printf("\n8.display");
printf("\n9.exit\n");
printf("\nenter the choice of operation to perform on linked list");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
do{
create_list();
display();
printf("do you want to create list ,y / n");
getchar();
scanf("%c",&ch1);
}while(ch1=='y');
break;
}
case 2:
{
int value;
printf("\nenter the value to be inserted");
scanf("%d",&value);
insert_at_begning(value);
display();
break;
}
case 3:
{
int value;
printf("\nenter value to be inserted");
scanf("%d",&value);
insert_at_end(value);
display();
break;
}
case 4:
{
insert_at_middle();
display();
break;
}
case 5:
{
delete_from_front();
display();
}break;
case 6:
{
delete_from_end();
display();
break;
}
case 7:
{
display();
delete_from_middle();
display();
break;
}
case 8:display();break;
case 9:
{
exit(0);
}
}
}
getch();
}
Executed Output:
TASK - 5 Date:
Problem Statement:
Write a Source Code to implement Stack operations using linked list

Source Code:
// C program to implement a stack using singly linked list
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

// Struct representing a node in the linked list


typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int new_data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}

// Struct to implement stack using a singly linked list


typedef struct Stack {
Node* head;
} Stack;

// Constructor to initialize the stack


void initializeStack(Stack* stack) { stack->head = NULL; }

// Function to check if the stack is empty


int isEmpty(Stack* stack) {

// If head is NULL, the stack is empty


return stack->head == NULL;
}

// Function to push an element onto the stack


void push(Stack* stack, int new_data) {

// Create a new node with given data


Node* new_node = createNode(new_data);

// Check if memory allocation for the new node failed


if (!new_node) {
printf("\nStack Overflow");
return;
}

// Link the new node to the current top node


new_node->next = stack->head;

// Update the top to the new node


stack->head = new_node;
}

// Function to remove the top element from the stack


void pop(Stack* stack) {

// Check for stack underflow


if (isEmpty(stack)) {
printf("\nStack Underflow\n");
return;
}
else {

// Assign the current top to a temporary variable


Node* temp = stack->head;

// Update the top to the next node


stack->head = stack->head->next;

// Deallocate the memory of the old top node


free(temp);
}
}

// Function to return the top element of the stack


int peek(Stack* stack) {

// If stack is not empty, return the top element


if (!isEmpty(stack))
return stack->head->data;
else {
printf("\nStack is empty");
return INT_MIN;
}
}

// Driver program to test the stack implementation


int main() {

// Creating a stack
Stack stack;
initializeStack(&stack);

// Push elements onto the stack


push(&stack, 11);
push(&stack, 22);
push(&stack, 33);
push(&stack, 44);

// Print top element of the stack


printf("Top element is %d\n", peek(&stack));

// removing two elemements from the top


printf("Removing two elements...\n");
pop(&stack);
pop(&stack);

// Print top element of the stack


printf("Top element is %d\n", peek(&stack));

return 0;
}

OUTPUT:
Linked List

30->20->10->NULL

Poped element = 30

After the pop, the new linked list

20->10->NULL

Poped element = 20

After the pop, the new linked list

10->NULL

Executed Output:
Problem Statement:
Write a Source Code to implement operations of Circular Singly Linked List

Source Code:
#include <stdio.h>
#include <stdlib.h>

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

struct Node* tail = NULL;

int isEmpty() {
return tail == NULL;
}

void insertAtEnd(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
if (isEmpty()) {
tail = newNode;
tail->next = newNode;
} else {
newNode->next = tail->next;
tail->next = newNode;
tail = newNode;
}
}

void insertAtBeginning(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
if (isEmpty()) {
tail = newNode;
tail->next = newNode;
} else {
newNode->next = tail->next;
tail->next = newNode;
}
}

void deleteFromBeginning() {
if (isEmpty()) {
printf("List is empty.\n");
return;
}
struct Node* temp = tail->next;
if (tail->next == tail) { // Only one node
tail = NULL;
} else {
tail->next = temp->next;
}
free(temp);
}

void deleteFromEnd() {
if (isEmpty()) {
printf("List is empty.\n");
return;
}
struct Node* current = tail->next;
if (tail->next == tail) { // Only one node
free(tail);
tail = NULL;
} else {
while (current->next != tail) {
current = current->next;
}
current->next = tail->next;
free(tail);
tail = current;
}
}

void traverse() {
if (isEmpty()) {
printf("List is empty.\n");
return;
}
struct Node* current = tail->next;
do {
printf("%d -> ", current->data);
current = current->next;
} while (current != tail->next);
printf("(head)\n");
}

int main() {
insertAtEnd(10);
insertAtEnd(20);
insertAtBeginning(5);
traverse(); // Output: 5 -> 10 -> 20 -> (head)
deleteFromBeginning();
traverse(); // Output: 10 -> 20 -> (head)
deleteFromEnd();
traverse(); // Output: 10 -> (head)
return 0;
}
OUTPUT:

Executed Output:
TASK - 6 Date:
Problem Statement:
Write a Source Code to sort elements using insertion sort.

Source Code: // to sort elements using insertion sort


#include <stdio.h> int main()
{

int n, array[1000], c, d, t, flag = 0;


printf("Enter number of elements\n"); scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) scanf("%d", &array[c]);
for (c = 1 ; c <= n - 1; c++) { t = array[c];
for (d = c - 1 ; d >= 0; d--) { if (array[d] > t) {
array[d+1] = array[d]; flag = 1;
}

else break;
}

if (flag) array[d+1] = t;
}

printf("Sorted list in ascending order:\n"); for (c = 0; c <= n - 1; c++) {


printf("%d\n", array[c]);
}

return 0;

Output:
Enter number of elements 5
Enter 5 integers
22
55
33
11
10
Sorted list in ascending order: 10
11
22
33
55
Executed Output:
Problem Statement:
Write a Source Code to sort elements using quick sort.

Source Code: // to sort elements using quick sort.


#include<stdio.h>
void quicksort(int number[25],int first,int last)
{
int i, j, pivot, temp;
if(first<last){ pivot=first; i=first; j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last) i++;
while(number[j]>number[pivot]) j--;
if(i<j){ temp=number[i]; number[i]=number[j]; number[j]=temp;
}

temp=number[pivot]; number[pivot]=number[j]; number[j]=temp; quicksort(number,first,j-1);


quicksort(number,j+1,last);
}

int main(){
int i, count, number[25];
printf("Enter the no of elements: "); scanf("%d",&count);
printf("Enter %d elements: ", count); for(i=0;i<count;i++)
scanf("%d",&number[i]); quicksort(number,0,count-1);
printf("Order of Sorted elements: "); for(i=0;i<count;i++)
printf(" %d",number[i]); return 0;
}

Output:
Enter the no of elements: 5
Enter 5 elements: 52 43 12 25 42
Order of Sorted elements: 12 25 42 43 52
Executed Output:
TASK - 7 Date:

Problem Statement:
Write a Source Code to sort the elements using merge sort.
Source Code: // to sort the elements using merge sort

#include<stdio.h>
void merge(int arr[],int min,int mid,int max)
{

int tmp[30]; int i,j,k,m; j=min; m=mid+1;


for(i=min; j<=mid && m<=max ; i++)
{

if(arr[j]<=arr[m])
{

tmp[i]=arr[j]; j++;
}
else
{

tmp[i]=arr[m]; m++;
}
}

if(j>mid)
{

for(k=m; k<=max; k++)


{

tmp[i]=arr[k]; i++;
}
}

else
{

for(k=j; k<=mid; k++)


{

tmp[i]=arr[k]; i++;
}
}

for(k=min; k<=max; k++) arr[k]=tmp[k];


}
void sortm(int arr[],int min,int max)
{
int mid; if(min<max)
{
mid=(min+max)/2; sortm(arr,min,mid); sortm(arr,mid+1,max);
merge(arr,min,mid,max);
}

int main()
{

int arr[30]; int i,size;


printf("\tMerge sort\n");
printf(" \n");
printf(" Enter no of elements for sorting "); scanf("%d",&size);
printf("\n Enter %d elements :\n ",size); for(i=0; i<size; i++)
{
scanf("%d",&arr[i]);
}

sortm(arr,0,size-1);
printf("\n Sorted elements after using merge sort:\n\n"); for(i=0; i<size; i++)
printf(" %d ",arr[i]); return 0;
}

Output: Merge sort

Enter no of elements for sorting 5 Enter 5 elements :


76
54
37
62
18
Sorted elements after using merge sort:
18 37 54 62 76
Executed Output:
TASK - 8 Date:

Problem Statement:
Write a Source Code to implement operations on trees

Source Code: // to implement operations on trees.

#include <stdio.h> #include <stdlib.h>

struct node { int data;

struct node *leftChild; struct node *rightChild;


};
struct node *root = NULL; 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 {
current = current->rightChild;

//insert to the right if(current == NULL) {


parent->rightChild = tempNode; return;
}
}
}
}
}

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


return NULL;
}
}

return current;
}
void pre_order_traversal(struct node* root) { if(root != NULL) {
printf("%d ",root->data); pre_order_traversal(root->leftChild); pre_order_traversal(root->rightChild);
}
}
void inorder_traversal(struct node* root) { if(root != NULL) {
inorder_traversal(root->leftChild); printf("%d ",root->data); inorder_traversal(root->rightChild);
}
}
void post_order_traversal(struct node* root) { if(root != NULL) {
post_order_traversal(root->leftChild); post_order_traversal(root->rightChild); printf("%d ", root-
>data);
}
}
int main() { int i;
int array[7] = { 17, 14, 25, 12, 19, 52, 41 };

for(i = 0; i < 7; i++) insert(array[i]);


i = 31;
struct node * temp = search(i);
if(temp != NULL) {
printf("[%d] Element found.", temp->data); printf("\n");
}else {
printf("[ x ] Element not found (%d).\n", i);
}
i = 15;
temp = search(i);
if(temp != NULL) {
printf("[%d] Element found.", temp->data); printf("\n");
}else {
printf("[ x ] Element not found (%d).\n", i);
}
printf("\nPreorder traversal: "); pre_order_traversal(root);
printf("\nInorder traversal: "); inorder_traversal(root);
printf("\nPost order traversal: "); post_order_traversal(root);
return 0;
}

Output:
Visiting elements: 17 25 52 41 [ x ] Element not found (31). Visiting elements: 17 14 [ x ] Element not
found (15).
Preorder traversal: 17 14 12 25 19 52 41
Inorder traversal: 12 14 17 19 25 41 52
Post order traversal: 12 14 19 41 52 25 17

Executed Output:
Problem Statement:
Write a Source Code to perform operations creation, insertion, deletion and traversing on a binary
search tree.
Source Code: // to perform operations creation, insertion, deletion and traversing on a BST
#include <stdio.h>
#include <stdlib.h>
// structure of a node struct node
{
int data;
struct node *left; struct node *right;
};

// globally initialized root pointer struct node *root = NULL;


// function prototyping
struct node *create_node(int); void insert(int);
struct node *delete (struct node *, int); int search(int);
void inorder(struct node *); void postorder();
void preorder();
struct node *smallest_node(struct node *); struct node *largest_node(struct node *);
int get_data();
int main()
{
int userChoice;
int userActive = 'Y'; int data;
struct node* result = NULL;

while (userActive == 'Y' || userActive == 'y')


{
printf("\n\n------- Binary Search Tree --------------- \n");
printf("\n1. Insert"); printf("\n2. Delete"); printf("\n3. Search");
printf("\n4. Get Larger Node Data"); printf("\n5. Get smaller Node data"); printf("\n\n-- Traversals --
");
printf("\n\n6. Inorder "); printf("\n7. Post Order "); printf("\n8. Pre Oder "); printf("\n9. Exit");

printf("\n\nEnter Your Choice: "); scanf("%d", &userChoice); printf("\n");

switch(userChoice)
{
case 1:
data = get_data(); insert(data); break;

case 2:
data = get_data();
root = delete(root, data); break;
case 3:
data = get_data();
if (search(data) == 1)
{
printf("\nData was found!\n");
}
else
{
printf("\nData does not found!\n");
}
break;
case 4:
result = largest_node(root); if (result != NULL)
{
printf("\nLargest Data: %d\n", result->data);
}
break;
case 5:
result = smallest_node(root); if (result != NULL)
{
printf("\nSmallest Data: %d\n", result->data);
}
break;
case 6: inorder(root); break;
case 7: postorder(root); break;
case 8: preorder(root); break;
case 9: printf("\n\nSource Code was terminated\n"); break;
default: printf("\n\tInvalid Choice\n"); break;
}
printf("\n \nDo you want to continue? "); fflush(stdin);
scanf(" %c", &userActive);
}
return 0;
}
// creates a new node
struct node *create_node(int data)
{
struct node *new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL)
{
printf("\nMemory for new node can't be allocated"); return NULL;
}
new_node->data = data; new_node->left = NULL; new_node->right = NULL;
return new_node;
}
// inserts the data in the BST void insert(int data)
{
struct node *new_node = create_node(data);

if (new_node != NULL)
{
// if the root is empty then make a new node as the root node if (root == NULL)
{
root = new_node;
printf("\n* node having data %d was inserted\n", data); return;
}
struct node *temp = root; struct node *prev = NULL;
// traverse through the BST to get the correct position for insertion while (temp != NULL)
{
prev = temp;
if (data > temp->data)
{
temp = temp->right;
}
else
{
temp = temp->left;
}
}
// found the last node where the new node should insert
if (data > prev->data)
{
prev->right = new_node;
}
else
{
prev->left = new_node;
}
printf("\n* node having data %d was inserted\n", data);
}
}
// deletes the given key node from the BST
struct node *delete (struct node *root, int key)
{
if (root == NULL)
{
return root;
}
if (key < root->data)
{
root->left = delete (root->left, key);
}
else if (key > root->data)
{
root->right = delete (root->right, key);
}
else
{
if (root->left == NULL)
{
struct node *temp = root->right; free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left; free(root);
return temp;
}
struct node *temp = smallest_node(root->right); root->data = temp->data;
root->right = delete (root->right, temp->data);
}
return root;
}
// search the given key node in BST int search(int key)
{
struct node *temp = root;

while (temp != NULL)


{
if (key == temp->data)
{
return 1;
}
else if (key > temp->data)
{
temp = temp->right;
}
else
{
temp = temp->left;
}
}
return 0;
}
// finds the node with the smallest value in BST struct node *smallest_node(struct node *root)
{
struct node *curr = root;
while (curr != NULL && curr->left != NULL)
{
curr = curr->left;
}
return curr;
}
// finds the node with the largest value in BST struct node *largest_node(struct node *root)
{
struct node *curr = root;
while (curr != NULL && curr->right != NULL)
{
curr = curr->right;
}
return curr;
}
// inorder traversal of the BST void inorder(struct node *root)
{
if (root == NULL)
{
return;
}
inorder(root->left); printf("%d ", root->data); inorder(root->right);
}
// preorder traversal of the BST void preorder(struct node *root)
{
if (root == NULL)
{
return;
}
printf("%d ", root->data); preorder(root->left); preorder(root->right);
}

// postorder travsersal of the BST void postorder(struct node *root)


{
if (root == NULL)
{
return;
}
postorder(root->left); postorder(root->right); printf("%d ", root->data);
}

// getting data from the user int get_data()


{
int data;
printf("\nEnter Data: "); scanf("%d", &data); return data;
}
Output:
------- Binary Search Tree ------

1. Insert
2. Delete
3. Search
4. Get Larger Node Data
5. Get smaller Node data

-- Traversals --

6. Inorder
7. Post Order
8. Pre Oder
9. Exit

Enter Your Choice: 1 Enter Data: 9


* node having data 9 was inserted
Do you want to continue? y
------- Binary Search Tree ------

1. Insert
2. Delete
3. Search
4. Get Larger Node Data
5. Get smaller Node data

-- Traversals --

6. Inorder
7. Post Order
8. Pre Oder
9. Exit

Enter Your Choice: 1 Enter Data: 8


Executed Output:
TASK - 9 Date:

Problem Statement:
Write a Source Code to implement Breadth First Search Graph Traversal Algorithm

Source Code: // to implement BFS Graph Traversal


#include <stdio.h> #include <stdlib.h> #include <stdbool.h>
#define MAX 5
struct Vertex { char label; bool visited;
};
//queue variables
int queue[MAX]; int rear = -1;
int front = 0;
int queueItemCount = 0;
//graph variables
//array of vertices
struct Vertex* lstVertices[MAX];
//adjacency matrix
int adjMatrix[MAX][MAX];
//vertex count
int vertexCount = 0;

//queue functions void insert(int data) {


queue[++rear] = data;
queueItemCount++;
}

int removeData() { queueItemCount--; return queue[front++];


}
bool isQueueEmpty() {
return queueItemCount == 0;
}

//graph functions
//add vertex to the vertex list void addVertex(char label) {
struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex)); vertex->label = label;
vertex->visited = false; lstVertices[vertexCount++] = vertex;
}
//add edge to edge array
void addEdge(int start,int end) { adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}

//display the vertex


void displayVertex(int vertexIndex) { printf("%c ",lstVertices[vertexIndex]->label);
}
//get the adjacent unvisited vertex
int getAdjUnvisitedVertex(int vertexIndex) { int i;

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


if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false) return i;
}

return -1;
}

void breadthFirstSearch() { int i;


//mark first node as visited lstVertices[0]->visited = true;
//display the vertex displayVertex(0);
//insert vertex index in queue insert(0);
int unvisitedVertex;
while(!isQueueEmpty()) {
//get the unvisited vertex of vertex which is at front of the queue int tempVertex = removeData();
//no adjacent vertex found
while((unvisitedVertex = getAdjUnvisitedVertex(tempVertex)) != -1)
{ lstVertices[unvisitedVertex]->visited = true; displayVertex(unvisitedVertex);
insert(unvisitedVertex);
}

//queue is empty, search is complete, reset the visited flag for(i = 0;i<vertexCount;i++) {
lstVertices[i]->visited = false;
}

int main() { int i, j;


for(i = 0; i<MAX; i++) { // set adjacency for(j = 0; j<MAX; j++) // matrix to 0
adjMatrix[i][j] = 0;
}
addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4

addEdge(0, 1); // S - A
addEdge(0, 2); // S - B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D

printf("\nBreadth First Search: "); breadthFirstSearch();

return 0;
}

Output:
Breadth First Search: S A B C D

Executed Output:
Problem Statement:
Write a Source Code to implement Depth First Search Graph Traversal Algorithm

Source Code: // to implement DFS Graph Traversal #include <stdio.h>


#include <stdlib.h> struct node {
int vertex;
struct node* next;
};
struct node* createNode(int v); struct Graph {
int totalVertices; int* visited;
struct node** adjLists;
};
void DFS(struct Graph* graph, int vertex) { struct node* adjList = graph->adjLists[vertex]; struct
node* temp = adjList;
graph->visited[vertex] = 1; printf("%d -> ", vertex); while (temp != NULL) {
int connectedVertex = temp->vertex;
if (graph->visited[connectedVertex] == 0) { DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node)); newNode->vertex = v;
newNode->next = NULL; return newNode;
}
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph)); graph->totalVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*)); graph->visited = malloc(vertices *
sizeof(int));
int i;
for (i = 0; i < vertices; i++) { graph->adjLists[i] = NULL; graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) { struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode; newNode = createNode(src);
newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode;
}
void displayGraph(struct Graph* graph) { int v;
for (v = 1; v < graph->totalVertices; v++) { struct node* temp = graph->adjLists[v]; printf("\n%d => ",
v);
while (temp) {
printf("%d, ", temp->vertex); temp = temp->next;
}
printf("\n");
}
printf("\n");
}
int main() {
struct Graph* graph = createGraph(8); addEdge(graph, 1, 5);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 3, 6);
addEdge(graph, 2, 7);
addEdge(graph, 2, 4);

printf("\nThe Adjacency List of the Graph is:"); displayGraph(graph);


printf("\nDFS traversal of the graph: \n"); DFS(graph, 1);
return 0;
}

Output:
The Adjacency List of the Graph is:
1 => 3, 2, 5,
2 => 4, 7, 1,
3 => 6, 1,
4 => 2,
5 => 1,
6 => 3,
7 => 2,
DFS traversal of the graph:
1 -> 3 -> 6 -> 2 -> 4 -> 7 -> 5 ->

Executed Output:
TASK - 10 Date:

Problem Statement:
Write a Source Code to implement the following Minimum Spanning Tree Algorithms:
Kruskal’s Algorithm

Source Code:
// C code to implement Kruskal's algorithm
#include <stdio.h>
#include <stdlib.h>
// Comparator function to use in sorting
int comparator(const void* p1, const void* p2)
{
const int(*x)[3] = p1;
const int(*y)[3] = p2;
return (*x)[2] - (*y)[2];
}
// Initialization of parent[] and rank[] arrays
void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
// Function to find the parent of a node
int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;
return parent[component]
= findParent(parent, parent[component]);
}
void unionSet(int u, int v, int parent[], int rank[], int n)
{
// Finding the parents
u = findParent(parent, u);
v = findParent(parent, v);

if (rank[u] < rank[v]) {


parent[u] = v;
}
else if (rank[u] > rank[v]) {
parent[v] = u;
}
else {
parent[v] = u;
// Since the rank increases if
// the ranks of two sets are same
rank[u]++;
}
}
// Function to find the MST
void kruskalAlgo(int n, int edge[n][3])
{
// First we sort the edge array in ascending order
// so that we can access minimum distances/cost
qsort(edge, n, sizeof(edge[0]), comparator);
int parent[n];
int rank[n];
// Function to initialize parent[] and rank[]
makeSet(parent, rank, n);

// To store the minimun cost


int minCost = 0;
printf(
"Following are the edges in the constructed MST\n");
for (int i = 0; i < n; i++) {
int v1 = findParent(parent, edge[i][0]);
int v2 = findParent(parent, edge[i][1]);
int wt = edge[i][2];
// If the parents are different that
// means they are in different sets so
// union them
if (v1 != v2) {
unionSet(v1, v2, parent, rank, n);
minCost += wt;
printf("%d -- %d == %d\n", edge[i][0],
edge[i][1], wt);
}
}
printf("Minimum Cost Spanning Tree: %d\n", minCost);
}
// Driver code
int main()
{
int edge[5][3] = { { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };
kruskalAlgo(5, edge);
Output:
Following are the edges in the constructed MST

2 -- 3 == 4

0 -- 3 == 5

0 -- 1 == 10

Minimum Cost Spanning Tree: 19

Executed Output:
Problem Statement:
Write a Source Code to implement the following Minimum Spanning Tree Algorithms:
Prim’s Algorithm

Source Code:
// A C program for Prim's Minimum
// Spanning Tree (MST) algorithm. The program is
// for adjacency matrix representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

// Number of vertices in the graph


#define V 5

// A utility function to find the vertex with


// minimum key value, from the set of vertices
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

// A utility function to print the


// constructed MST stored in parent[]
int printMST(int parent[], int graph[V][V])
{
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
printf("%d - %d \t%d \n", parent[i], i,
graph[i][parent[i]]);
}

// Function to construct and print MST for


// a graph represented using adjacency
// matrix representation
void primMST(int graph[V][V])
{
// Array to store constructed MST
int parent[V];
// Key values used to pick minimum weight edge in cut
int key[V];
// To represent set of vertices included in MST
bool mstSet[V];
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is picked as first
// vertex.
key[0] = 0;

// First node is always root of MST


parent[0] = -1;

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex from the


// set of vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of


// the adjacent vertices of the picked vertex.
// Consider only those vertices which are not
// yet included in MST
for (int v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent


// vertices of m mstSet[v] is false for vertices
// not yet included in MST Update the key only
// if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false
&& graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

// print the constructed MST


printMST(parent, graph);
}

// Driver's code
int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

// Print the solution


primMST(graph);

return 0;
}
Output:
Edge Weight

0-1 2

1-2 3

0-3 6

1-4 5

Executed Output:

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