0% found this document useful (0 votes)
19 views47 pages

DATA STRUCTURE RECORD Update

Jfspypy

Uploaded by

truthordare026
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)
19 views47 pages

DATA STRUCTURE RECORD Update

Jfspypy

Uploaded by

truthordare026
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/ 47

SETHU INSTITUTE OF TECHNOLOGY

(An Autonomous Institution | Accredited with ‘A++’ Grade by NAAC)


PULLOOR, KARIAPATTI - 626 115

DEPARTMENT OF CSE

(ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING)

LAB RECORD

SEMESTER: III

R21UIT307-DATA STRUCTURES LABORATORY


(Common to CSE,IT,AIDS,CSD,AIML, IoT & Cyber Security)

NAME :

ROLL No :

REG. No :

DEPT :
SETHU INSTITUTE OF TECHNOLOGY
PULLOOR-626 115, KARIAPATTI TALUK
VIRUDHUNAGAR DISTRICT

PRACTICAL RECORD

BONAFIDE CERTIFICATE

Certified that this bonafide record of work done


by…………………………………………………………...in……………………
the…………………………………………………..................................…. during the
year……………………………

Faculty In-charge Head of the Department

Register Number:

Submitted for the Practical Examination held on …………………………….

INTERNAL EXAMINER EXTERNAL EXAMINER


INSTITUTE VISION
To promote excellence in technical education and scientific research for the benefit of
the society.
INSTITUTE MISSION
 To provide quality technical education to fulfill the aspiration of the student and to meet
the needs of the Industry. 
 To provide holistic learning ambience.
 To impart skills leading to employability and entrepreneurship.
 To establish effective linkage with industries.
 To promote Research and Development activities.
 To offer services for the development of society through education and technology.

CORE VALUES
 Quality  Commitment  Innovation  Team work  Courtesy

QUALITY POLICY
 To provide Quality technical education to the students
 To produce competent professionals and contributing citizens
 To contribute for the upliftment of the society

DEPARTMENT VISION
• To promote excellence in producing competent IT professionals to serve the society
through technology and research.

DEPARTMENT MISSION
 Producing Competent Professionals in Information and Communication Technologies
 Educating the Students with the State of Art Computing Environment and Pedagogical
Innovations
 Encouraging Entrepreneurship and Imparting Skills for Employability
 Establishing Collaboration with IT and Allied Industries
 Promoting Research in Information and Communication Technology to Improve the
Quality of Human Life
 Offering Beneficial Service to the Society by Inculcating Knowledge and Providing IT
Solutions

PROGRAM EDUCATIONAL OBJECTIVES

Exhibit Proficiency in Analyzing, Designing and Developing IT Based Solutions to


PEO 1
Cater to the Business and Societal Needs. {Technical Competence}
Provide Professional Expertise to the Industry and Society with Effective
PEO 2
Communication and Ethics. {Professionalism}
Engage in Lifelong Learning for Professional Development and Research. {Life-
PEO 3 Long Learning}
PROGRAM SPECIFIC OUTCOMES
PSO – 1 Design Software Solutions Using Programming Skills and Computing
Technologies.
PSO – 2 Design and Implement Data Communication System Using Various IT
Components.

PROGRAM OUTCOMES
Apply the knowledge of Mathematics, Basic Science, Computer and communication
1. Fundamentals to solve complex problems in Information Technology. [Engineering
Knowledge]
Identify, formulate, review research literature and analyze complex problems reaching
2. concrete conclusions using principles of mathematics, Engineering sciences and
Information Technology. [Problem Analysis]
Design solution for complex information and communication engineering problems and
design system components or processes that meet with realistic constraints for public health
3.
and safety, cultural, societal and environment considerations.
[Design/Development of Solutions]
Conduct investigations of complex Information technology related problems using research
based knowledge and research methods including design of experiments, analysis and
4.
interpretation of data to provide valid conclusions through synthesis of information.
[Conduct investigations of complex problems]
Create, select and apply appropriate techniques, resources and modern IT tools including
5. prediction and modeling to complex engineering activities with an understanding of the
limitations. [Modern Tool Usage]
Apply reasoning informed by contextual knowledge to assess societal, health, safety, legal
6. and cultural issues and consequent responsibilities relevant to professional engineering
practice. [The Engineer and Society]
Understand the impact of professional engineering solutions in societal and environmental
7. contexts and demonstrate the knowledge of and need for sustainable development.
[Environment and sustainability]
Apply ethical principles and commit to professional ethics and responsibilities through the
8.
norms of professional engineering practice. [Ethics]
Function effectively as an individual and as a member or leader in diverse teams and in
9.
multidisciplinary settings. [Individual and Team Work]
Communicate effectively with the engineering community and the society at large, such as,
10. being able to comprehend and write effective reports and design documentation, make
effective presentations and give and receive clear instructions. [Communication]
Demonstrate knowledge and understanding of engineering and management principles and
11. apply these to one‟s own work, as a member /or leader in a team, to manage projects in
multi-disciplinary environment. [Project Management and Finance]
Recognize the need for, and have the preparation and ability to engage in independent and
12.
Life-long learning in broadest context of technological change. [Life-long Learning]
EX. EXPERIMENT PAGE
NO. DATE EXPERIMENT NO.
MARKS SIGNATURE

Simple C Programs
a. Programs using recursion
1. b. Programs using structures
c. Programs using pointers
Linked List Implementation of List
ADT
2. a. Implementation of Singley
Linked List
b. Implementation of Doubly
Linked list
3. Array implementation of stack ADT
Linked list implementations of stack
4.
ADT
Checking „Balanced Parentheses‟
5.
using Array implementation of stack
Implementation of queue using
6. a. Arrays
b. Linked List
Binary Search Trees –
7.
implementation
Implementation of Dijkstra‟s
8.
Algorithm
Implementation of minimum
spanning tree using
9. a. Kruskal algorithm
b. Prims algorithm

Program to sort set of elements


using
10. a. Insertion sort
b. Merge sort
c. Quick sort
Ex. No. : 1 (a)
PROGRAMS USING RECURSION
Date :

AIM : To write a Simple C Programs for the following programs


a. Programs using recursion
b. Programs using structures
c. Programs using pointers

Factorial of a number using Recursion

ALGORITHM :

The program calculates the factorial of a number using a recursive function. The base
case is factorial(0) = 1, and the recursive step is n * factorial(n - 1).

Step 1 : Read the input number n.


Step 2 : Call the recursive function factorial(n):
If n == 0, return 1 (base case).
Otherwise, return n * factorial(n - 1) (recursive step).
Step 3 : The recursion continues until n reaches 0.

PROGRAM :

#include <stdio.h>
int factorial(int n)
{
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}/

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

printf("Factorial of %d is %d\n", num, factorial(num));


return 0;
}
Ex. No. : 1 (b)
PROGRAMS USING STRUCTURES
Date :

Program to store and display student information using structures

This program defines a Student structure with fields for the student's name, roll number,
and marks. It then reads this information from the user and displays it.

ALGORITHM :
Step 1 : Define a structure Student with the fields: name, roll, and marks.
Step 2 : Declare a variable of type Student.
Step 2 : Input the student's name, roll number, and marks.
Step 4 : Store these values in the respective fields of the structure.
Step 5 : Print the stored student's name, roll number, and marks.

PROGRAM :

#include <stdio.h>
struct Student {
char name[50];
int roll;
float marks;
};

int main() {
struct Student s;
printf("Enter student's name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("\nStudent Information:\n");
printf("Name: %s\n", s.name);
printf("Roll Number: %d\n", s.roll);
printf("Marks: %.2f\n", s.marks);
return 0;
}
Ex. No. : 1(c)
PROGRAMS USING POINTERS
Date :

Program to swap two numbers using pointers


This program uses pointers to swap two numbers. The swap() function takes the
addresses of two variables, and the swapping is done by manipulating their memory locations
using pointers.

ALGORITHM :

Step 1 : Read two numbers a and b.


Step 2 : Call the function swap(&a, &b):
Step 3 : Inside swap(), store the value of *x (i.e., a) in a temporary variable.
Step 4 : Assign the value of *y (i.e., b) to *x.
Step 5: Assign the temporary variable's value to *y.
Step 6 : The values of a and b are now swapped.
Step 7 : Print the swapped values of a and b.

PROGRAM :
#include <stdio.h>

void swap(int *x, int *y) {


int temp;
temp = *x;
*x = *y;
*y = temp;
}

int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}

RESULT : Thus the program for Simple C Programs using recursion, using structures and using
pointers was verified and executed successfully
Ex. No. : 2 (a)
IMPLEMENTATION OF SINGLY LINKED LIST
Date :

AIM
To Write a C program that uses functions to perform the following:
a) Create a singly linked list of integers.
b) Delete a given integer from the above linked list.
c) Display the contents of the above list after deletion.

ALGORITHM
Step 1: Include all the header files which are used in the program.
Step 2: Declare all the user defined functions.
Step 3: Define a Node structure with two members data and next
Step 4: Define a Node pointer 'head' and set it to NULL.
Step 5: Implement the main method by displaying operations menu and make suitable
function calls in the main method to perform user selected operation [Insert,
Routine, Delete Route, Display]
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

**NODE CREATION
struct node
{
int data;
struct node* link;
}*root;
void add();
int length();
void display();
void delet();
void exit();
void main()
**FUNCTION CALL
{
while(1)
{
int ch;
int len;
printf("enter the operation");
printf("1.add\n");
printf("2.display\n");
printf("f3. delete\n");
printf("4. length\n");
printf("5. quit\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
add();
break;
case 2:
display();
break;
case 3:
delet();
break;
case 4:
len=length();
printf("%d", len);
break;
case 5:
exit(1);
default: printf("invalid");
}
}
}
//INSERTION OF ELEMENTS
void add()
{
struct node* temp;
temp =(struct node*)malloc (sizeof(struct node));
printf("enter the data");
scanf("%d", &temp->data);
temp->link=NULL;
if(root==NULL)
{
root =temp;
}
else
{
struct node* p;
p=root;
while(p->link!=NULL)
{
p=p->link;
}
p-> link=temp;
}
}
//FINDING LENGTH OF INSERTED ELEMENT
int length()
{
int count =0;
struct node * temp;
temp=root;
while(temp!=NULL)
{
count++;
temp=temp->link;
}
return count;
}
//DISPLAY ELEMENTS
void display()
{
struct node* temp;
temp=root;
if(temp==NULL)
{
printf("empty");
}
else
{
while(temp!=NULL)
{
printf("%d==>", temp->data);
temp=temp->link;
}
printf("\n \n");
}
}
//DELETING ELEMENT
void delet()
{
int loc;
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("enter location to delete");
scanf("%d", &loc);
if(loc>length())
{
printf("invalid");
}
else if(loc==1)
{
temp=root;
root=temp->link;
temp->link=NULL;
free(temp);
}
else
{
struct node *p=root, *q;
int i=1;
while(i<loc-1)
{
p=p->link;
i++;
}
q=p->link;
p->link= q->link;
q->link==NULL;
free(q);
}
}

RESULT : Thus the implementation for Singly linked list program was verified and executed.
Ex. No. : 2 (b)
IMPLEMENTATION OF DOUBLY LINKED LIST
:
Date

AIM :
To Write a C program that uses functions to perform the following:
a) Create a doubly linked list of integers.
b) Delete a given integer from the above doubly linked list.
c) Display the contents of the above list after deletion.
ALGORITHM :
Step 1: Include all the header files which are used in the program.
Step 2: Declare all the user defined functions.
Step 3: Define a Node structure with two membersdata and next
Step 4: Define a Node pointer 'head' and set it to NULL.
Step 4: Implement the main method by displaying operations menu and make suitable
function calls in the main method to perform user selected operation.
In a double linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display
Insertion
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Deletion
In a double linked list, the deletion operation can be performed in three ways as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
Displaying a Double Linked List
We can use the following steps to display the elements of a double linked list...
Step 1: Check whether list is Empty (head == NULL)
Step 2: If it is Empty, then display 'List is Empty!!!' and terminate the function.
Step 3: If it is not Empty, then define a Node pointer 'temp' and initialize with head.
Step 4: Display 'NULL <--- '.
Step 5: Keep displaying temp → data with an arrow (<===>) until temp reaches to the
last node
Step 6: Finally, display temp → data with arrow pointing to NULL (temp → data --->
NULL).
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node*left;
struct node*right;
};
struct node*root;
void insert();
void delet();
void display();
int length();
void exit();
int main()
{
int ch,len;
clrscr();
while(1)
{
printf("\n1. add 2.delete 3. display .4. lenght 5. exit\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
delet();
break;
case 3:
display();
break;
case 4:
len=length();
printf("The length is: %d", len);
break;
case 5:
exit(-1);
break;
default: printf("invalid");
break;
}
}
}
void insert()
{
struct node*temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->right=NULL;
temp-> left=NULL;
scanf("%d", &temp->data);
if(root==NULL)
{
root=temp;
}
else
{
struct node *p;
p=root;
while(p->right!=NULL)
{
p=p->right;
}
p->right=temp;
temp->left=p;
}
}
int length()
{

int count=0;
struct node*temp=root;
while(temp!=NULL)
{
count++;
temp=temp->right;
}
Printf(“%d”, count);
return count;
}
void delet()
{
struct node *p;
p=root;
root=p->right;
root->left=p->left;
p->left->right=root;
free(p);
}
void display()
{
struct node *temp=root;
if(temp==NULL)
{
printf("Empty");
}
else
{
while(temp!=NULL)
{
printf("%d->", temp->data);
temp=temp->right;
}
}
}

RESULT : Thus the implementation of Doubly linked list program was verified and executed
Ex. No. : 3
ARRAY IMPLEMENTATION OF STACK ADT
Date :

AIM :
To Write a C program that uses functions to perform the following:
a) Create stack and push integer into stack
b) pop integer from the above stack
c) Display the contents of the stack.
ALGORITHM :
A stack can be implemented using array as follows...
Before implementing actual operations, first follow the below steps to create an empty stack.
Step 1: Include all the header files which are used in the program and define a constant
'SIZE' with specific value.
Step 2: Declare all the functions used in stack implementation.
Step 3: Create a one dimensional array with fixed size (intstack[SIZE])
Step 4: Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5: In main method display menu with list of operations and make suitable function
calls to perform operation selected by the user on the stack.

PROGRAM :
STACK USING LIST
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* head;
void push();
void pop();
void display();
int count();
int main()
{
int ch,len;
clrscr();
while(1)
{
printf("\nEnter your choice\n ");
printf("1. Push \n 2. Pop \n 3. display \n 4.count \n 5. exit\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:

len=count();
printf("The length of the List is: %d\n", len);
break;
case 5:
exit(1);
break;
case 6:
default:
printf("\nInvalid Number\n");
break;
} }

return 0;
}
void push()
{
struct node* temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter the number to be inserted\n");
scanf("%d", &temp->data);
temp->link=head;
head=temp;
}
void pop()
{
struct node* temp;
if(head==NULL)
printf("Empty");
temp=head;
head=head->link;
free(temp);
printf("The number is popped Out\n");
}
void display()
{
struct node* temp;
temp=head;
if(temp==NULL)
printf("empty");
else
{
while(temp!=NULL)
{
printf("%d ", temp->data);
printf("\t");temp=temp->link;
}
printf("\t");
} }
int count()
{
int len=0;
struct node* temp;
temp=head;
while(temp!=NULL)
{
len++;
temp=temp->link;
}
return len;
}

RESULT : Thus the implementation of Stack ADT using array program was verified and
executed successfully
Ex. No. : 4
LINKED LIST IMPLEMENTATION OF STACK ADT
Date :

AIM : To write a c program to implement stack ADT using linked list

ALGORITHM :

To implement stack using linked list, we need to set the following things before implementing
actual operations.
Step 1: Include all the header files which are used in the program. And declare all the
user defined functions.
Step 2: Define a 'Node' structure with two membersdata and next.
Step 3: Define a Node pointer 'top' and set it to NULL.
Step 4: Implement the main method by displaying Menu with list of operations and
make suitable function calls in the main method.

LINKED LIST IMPLEMENTATION OF STACK


PROGRAM :

#include<stdio.h>
#include<conio.h>
static top=0;
const max=50;
struct stack
{
int data;
}st[50];
void push()
{
int num;
if(top>=max)
printf("Stack is full\n");
else
{
printf("Enter the number\n");
scanf("%d",&num);
st[top].data=num;
top=top+1;
}
}
void pop()
{
int num,x;
if(top!=NULL)
{
top=top-1;
x=1;
if(x==1)
printf("%d is poped",st[top].data);
}
else
printf("The stack is empty\n");
}
void disp()
{
int i;
if(top!=NULL)
{
for(i=0;i<top;i++)
printf("%d\t",st[i].data);
}
else
printf("The stack is empty\n");
}
void main()
{
int ch;
while(1)
{
printf("\n1.push\t2.pop\t3.display\t4.exit");
printf("\nEnter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
disp();
break;
case 4:
exit(-1);
break;
default:
printf("Enter correct choice\n");
break;
}
}
}

RESULT : Thus the implementation of Stack ADT program using linked list was executed
successfully
Ex. No. : 5 CHECKING ‘BALANCED PARENTHESES’ USING ARRAY

Date : IMPLEMENTATION OF STACK

AIM : To write a C program for Checking „Balanced Parentheses‟ using Array implementation
of stack

ALGORITHM:
Step 1 : Create an empty stack to keep track of opening brackets
Step 2 : Iterate through each character in the message.
Step 3 : If the character is an opening bracket ('['), push it onto the stack.
Step 4 : If the character is a closing bracket (']'), pop from the stack and check if the popped
bracket is the corresponding opening bracket ('[').
Step 5 : If the stack is empty when trying to pop, or the brackets do not match, return false.
Step 6 : After processing the entire message, check if the stack is empty. If it is, return true;
otherwise, return false.

PROGRAM :

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 30
int top=-1;
int stack[MAX];
void push(char);
char pop();
int match(char a,char b);
int check(char []);
int main()
{
char exp[MAX]; int valid;
printf("Enter an algebraic expression : "); gets(exp);
valid=check(exp); if(valid==1)
printf("Valid expression\n");
else
printf("Invalid expression\n");
return 0;
}
int check(char exp[] )
{
int i;
char temp; for(i=0;i<strlen(exp);i++)
{
if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[') push(exp[i]);
if(exp[i]==')' || exp[i]=='}' || exp[i]==']') if(top==-1)
/*stack empty*/

{
}
else
{
printf("Right parentheses are more than left parentheses\n")
return 0;
temp=pop();
if(!match(temp, exp[i]))
{
printf("Mismatched parentheses are : ");
printf("%c and %c\n",temp,exp[i]);
return 0;
}
}
}
if(top==-1) /*stack empty*/
{
printf("Balanced Parentheses\n"); return 1;
}
else
{
printf("Left parentheses more than right parentheses\n");
return 0;
}
}
/*End of main()*/

int match(char a,char b)


{
if(a=='[' && b==']') return 1;
if(a=='{' && b=='}') return 1;
if(a=='(' && b==')') return 1;
return 0;
}
/*End of match()*/
void push(char item)
{
if(top==(MAX-1))
{
printf("Stack Overflow\n"); return;
}
top=top+1; stack[top]=item;
}
/*End of push()*/
char pop()
{
if(top==-1)
{
printf("Stack Underflow\n");
exit(1);
}
return(stack[top--]);
}
/*End of pop()*/

RESULT: Thus a C program for Checking „Balanced Parentheses‟ using Array implementation
of stack is executed successfully
Ex. No. : 6 (a)
IMPLEMENTATION OF QUEUE USING ARRAYS
Date :

AIM
Write C programs to implement a queue ADT using
i) array and ii) linked list respectively.
ALGORITHMS
Queue data structure using array can be implemented as follows...
Before we implement actual operations, first follow the below steps to create an empty queue.
Step 1: Include all the header files which are used in the program and define a constant
'SIZE' with specific value.
Step 2: Declare all the user defined functions which are used in queue implementation.
Step 3: Create a one dimensional array with above defined SIZE (intqueue[SIZE])
Step 4: Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int
front = -1, rear = -1)
Step 5: Then implement main method by displaying menu of operations list and make
suitable function calls to perform operation selected by the user on queue.

To implement queue using linked list, we need to set the following things before implementing
actual operations.
Step 1: Include all the header files which are used in the program. And declare all the
user defined functions.
Step 2: Define a 'Node' structure with two membersdata and next.
Step 3: Define two Node pointers 'front' and 'rear' and set both to NULL.
Step 4: Implement the main method by displaying Menu of list of operations and make
suitable function calls in the main method to perform user selected operation.
PROGRAM
QUEUE USING ARRAY IMPLEMENTATION
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void enQueue();
void deQueue();
void display();
int queue[SIZE], front = -1, rear = -1;
int main()
{
int data, ch;
while(1)
{
printf("\n1.Insertion\t2. Deletion\t3. Display\t4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch){
case 1:
enQueue();
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(-1);
break;
default: printf("\nInvalid!!!");
}
}
}
void enQueue()
{
int data;
if(rear == SIZE-1)
printf("\nQueue is Full!!!");
else
{
printf("Enter Element ");
scanf("%d", &data);
if(front == -1)
front = 0;
rear++;
queue[rear] = data;
printf("\nInserted");
}
}
void deQueue(){
if(front == rear)
printf("\nQueue is Empty!!!");
else{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
else{
int i;
printf("\nElements are:\n");
for(i=front; i<=rear; i++)
printf("%d,\t",queue[i]);
}
}

RESULT: Thus the program QUEUE ADT using array was executed successfully
Ex. No. : 6 (b)
IMPLEMENTATION OF QUEUE USING LINKED LIST
Date :

LINKED LIST IMPLEMENTATION

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;
void insert();
void delete();
void display();
void main()
{
int ch;
while(1)
{
printf("1. Insert\t2. Delete\t3. Display\t4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&ch);
switch(ch){
case 1:
insert();
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(-1);
default: printf("\nInvalid\n");
}}}
void insert()
{

int a;
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
scanf("%d", &a);
newNode->data = a;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
rear -> next = newNode;
rear = newNode;
}
printf("Inserted\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
} }
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
} }

RESULT: Thus the program QUEUE ADT using array and linked list was verified and executed
Successfully
Ex. No. : 7
BINARY SEARCH TREES – IMPLEMENTATION
Date :

AIM : To write a „C‟ program to perform the binary search tree implementation

ALGORITHM :

Step 1 : If the root is NULL:


Return NULL (base case for recursion).
Step 2 : If the value to be deleted (x) is greater than the key of the current root:
Recursively call delete with the right subtree of the current root and the
value x.
Update the right child of the current root with the result of the recursive
call.
Step 3 : If the value to be deleted (x) is smaller than the key of the current root:
Recursively call delete with the left subtree of the current root and the
value x.
Update the left child of the current root with the result of the recursive
call.
Step 4 : If the value to be deleted (x) is equal to the key of the current root:
If the current node has no child:
 Free the current node.
 Return NULL.
If the current node has one child:
 Set temp to the non-null child of the current node.
 Free the current node.
 Return temp.
If the current node has two children:
 Find the minimum node in the right subtree (temp).
 Replace the key of the current node with the key of temp.
 Recursively call delete with the right subtree of the current node
and the key of temp.
Step 5 : Return the current node (the root of the modified tree).
PROGRAM:
#include <stdio.h>
#include <stdlib.h>

// Define a structure for a binary tree node


struct BinaryTreeNode {
int key;
struct BinaryTreeNode *left, *right;
};

struct BinaryTreeNode* newNodeCreate(int value)


{
struct BinaryTreeNode* temp
= (struct BinaryTreeNode*)malloc(
sizeof(struct BinaryTreeNode));
temp->key = value;
temp->left = temp->right = NULL;
return temp;
}

// Function to search for a node with a specific key in the tree


struct BinaryTreeNode*
searchNode(struct BinaryTreeNode* root, int target)
{
if (root == NULL || root->key == target) {
return root;
}
if (root->key < target) {
return searchNode(root->right, target);
}
return searchNode(root->left, target);
}

// Function to insert a node with a specific value in the tree


struct BinaryTreeNode*
insertNode(struct BinaryTreeNode* node, int value)
{
if (node == NULL) {
return newNodeCreate(value);
}
if (value < node->key) {
node->left = insertNode(node->left, value);
}
else if (value > node->key) {
node->right = insertNode(node->right, value);
}
return node;
}

// Function to perform post-order traversal


void postOrder(struct BinaryTreeNode* root)
{
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf(" %d ", root->key);
}
}

// Function to perform in-order traversal


void inOrder(struct BinaryTreeNode* root)
{
if (root != NULL) {
inOrder(root->left);
printf(" %d ", root->key);
inOrder(root->right);
}
}

// Function to perform pre-order traversal


void preOrder(struct BinaryTreeNode* root)
{
if (root != NULL) {
printf(" %d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}

// Function to find the minimum value


struct BinaryTreeNode* findMin(struct BinaryTreeNode* root)
{
if (root == NULL) {
return NULL;
}
else if (root->left != NULL) {
return findMin(root->left);
}
return root;
}

// Function to delete a node from the tree


struct BinaryTreeNode* delete (struct BinaryTreeNode* root,
int x)
{
if (root == NULL)
return NULL;

if (x > root->key) {
root->right = delete (root->right, x);
}
else if (x < root->key) {
root->left = delete (root->left, x);
}
else {
if (root->left == NULL && root->right == NULL) {
free(root);
return NULL;
}
else if (root->left == NULL
|| root->right == NULL) {
struct BinaryTreeNode* temp;
if (root->left == NULL) {
temp = root->right;
}
else {
temp = root->left;
}

free(root);
return temp;
}
else {
struct BinaryTreeNode* temp
= findMin(root->right);
root->key = temp->key;
root->right = delete (root->right, temp->key);
}
}

return root;
}

int main()
{
// Initialize the root node
struct BinaryTreeNode* root = NULL;

// Insert nodes into the binary search tree


root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);
insertNode(root, 80);

// Search for a node with key 60


if (searchNode(root, 60) != NULL) {
printf("60 found");
}
else {
printf("60 not found");
} printf("\n");

// Perform post-order traversal


postOrder(root);
printf("\n");

// Perform pre-order traversal


preOrder(root);
printf("\n");

// Perform in-order traversal


inOrder(root);
printf("\n");

// Perform delete the node (70)


struct BinaryTreeNode* temp = delete (root, 70);
printf("After Delete: \n");
inOrder(root);
return 0;
}

RESULT : Thus the implementation of Binary Seach Tree program was verified and executed
Ex. No. : 8
DIJKSTRA’S ALGORITHM IMPLEMENTATION
Date :

AIM: To write a „C‟ program to implement the Dijkstra‟s algorithm

ALGORITHM
Step1: Start the program.
Step2: Read the number of vertices
Step3: Read the weight of every pair of vertices.
Step4: Get the source vertex & destination.
Step5: Construct the graph.
Step6: Start finding the start node to all other neighboring nodes.
Step7: Nearest path is selected using array until the end node is reached.
Step8: Print the shortest path.
Step9: Terminate the program

PROGRAM CODING :
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. 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]);

printf("\nEnter the starting node:");


scanf("%d",&u);
dijkstra(G,n,u);

return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node


//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]


for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}

distance[startnode]=0;
visited[startnode]=1;
count=1;

while(count<n-1)
{
mindistance=INFINITY;

//nextnode gives the node at minimum distance


for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}

//check if a better path exists through nextnode


visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);

j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}

RESULT : Thus the program for Dijkstra‟s algorithm was executed and the output is verified
Ex. No. : 9 (a)
IMPLEMENTATION OF MINIMUM SPANNING TREE USING
Date : KRUSKAL ALGORITHM

AIM :

The aim is to implement a Minimum Spanning Tree (MST) using both Kruskal's
Algorithm and Prim's Algorithm, and to understand how these algorithms work for finding the
MST of a connected, weighted graph.

Kruskal's Algorithm

ALGORITHM :

Start from the edges with the lowest weight and keep adding edges until we reach our goal.

The steps for implementing Kruskal's algorithm are as follows:


Step 1 : Sort all the edges from low weight to high
Step 2 : Take the edge with the lowest weight and add it to the spanning tree. If adding
the edge created a cycle, then reject this edge.
Step 3 : Keep adding edges until we reach all vertices.

PROGRAM :

#include <stdio.h>
#define MAX 100
#define INF 9999

typedef struct {
int u, v, w;
} Edge;

Edge edges[MAX];
int parent[MAX];

int find(int i) {
while (parent[i] != i)
i = parent[i];
return i;
}

void union1(int i, int j) {


int a = find(i);
int b = find(j);
parent[a] = b;
}
void kruskal(int n, int e) {
Edge result[MAX];
int i, j, count = 0, mincost = 0;

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


parent[i] = i;

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


int a = find(edges[i].u);
int b = find(edges[i].v);
if (a != b) {
result[count++] = edges[i];
union1(a, b);
mincost += edges[i].w;
}
}

printf("Minimum Spanning Tree Edges:\n");


for (i = 0; i < count; i++)
printf("Edge (%d, %d) -> Weight = %d\n", result[i].u, result[i].v, result[i].w);
printf("Minimum cost = %d\n", mincost);
}

int main() {
int n, e, i;
printf("Enter number of vertices: ");
scanf("%d", &n);
printf("Enter number of edges: ");
scanf("%d", &e);

printf("Enter the edges with their weights (u v w):\n");


for (i = 0; i < e; i++) {
scanf("%d %d %d", &edges[i].u, &edges[i].v, &edges[i].w);
}

// Sort edges by weight


for (i = 0; i < e - 1; i++) {
for (int j = 0; j < e - i - 1; j++) {
if (edges[j].w > edges[j + 1].w) {
Edge temp = edges[j];
edges[j] = edges[j + 1];
edges[j + 1] = temp;
}
}
}

kruskal(n, e);
return 0; }
Ex. No. : 9 (b)
IMPLEMENTATION OF MINIMUM SPANNING TREE USING
Date : PRIMS ALGORITHM

ALGORITHM :

Step 1: Initialize a set of vertices (MST set) that are included in the MST.
Step 2 : For every vertex not in the MST, select the smallest edge connecting the vertex
to the MST.
Step 3 : Add this vertex to the MST.
Step 4 : Repeat step 2 until all vertices are included in the MST

PROGRAM :

#include <stdio.h>

#define MAX 100


#define INF 9999

int G[MAX][MAX], n;

void prim() {
int selected[MAX], i, j, ne = 0;
int min, x, y, mincost = 0;

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


selected[i] = 0;
selected[0] = 1;

printf("Minimum Spanning Tree Edges:\n");

while (ne < n - 1) {


min = INF;
for (i = 0; i < n; i++) {
if (selected[i]) {
for (j = 0; j < n; j++) {
if (!selected[j] && G[i][j]) {
if (min > G[i][j]) {
min = G[i][j];
x = i;
y = j;
}
}
}
}
}

printf("Edge (%d, %d) -> Weight = %d\n", x, y, G[x][y]);


mincost += G[x][y];
selected[y] = 1;
ne++;
}

printf("Minimum cost = %d\n", mincost);


}

int main() {
int i, j;
printf("Enter number of vertices: ");
scanf("%d", &n);

printf("Enter the adjacency matrix (enter 9999 for infinity):\n");


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &G[i][j]);
if (G[i][j] == 0)
G[i][j] = INF;
}
}

prim();
return 0;
}

RESULT: Thus the implementation of a Minimum Spanning Tree (MST) using both Kruskal's
Algorithm and Prim's Algorithm is executed and output was verified successfully.
Ex. No. : 10 (a)
PROGRAM TO SORT SET OF ELEMENTS USING
Date : INSERTION SORT

AIM: To write a C program to sort set of elements using


a. Insertion sort b. Merge sort c. Quick sort

a. INSERTION SORT
ALGORITHM :

Step 1 : Start from the second element in the array.


Step 2 : Compare it with the previous elements, shifting larger elements to the right.
Step 3 : Insert the current element in its correct position.
Step 4 : Repeat the process for all elements.

PROGRAM :

#include <stdio.h>

void insertionSort(int arr[], int n) {


int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
insertionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Ex. No. : 10 (b)
PROGRAM TO SORT SET OF ELEMENTS USING
Date : MERGE SORT

b. MERGE SORT

ALGORITHM :

Step 1 : Divide the array into two halves.


Step 2 : Recursively sort each half.
Step 3 : Merge the two sorted halves into one sorted array

PROGRAM :

#include <stdio.h>

void merge(int arr[], int l, int m, int r) {


int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Temporary arrays
int L[n1], R[n2];

// Copy data to temporary arrays L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

// Merge the temp arrays back into arr[l..r]


i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if any


while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
Ex. No. : 10 (c)
PROGRAM TO SORT SET OF ELEMENTS USING
Date : QUICK SORT

c. QUICK SORT

ALGORITHM:

Step 1 :Pick an element as a pivot (can be the first, last, or random element).
Step 2 :Partition the array such that elements less than the pivot are on the left, and those
greater are on the right.
Step 3: Recursively apply the same process to the left and right subarrays.

PROGRAM :

#include <stdio.h>

void swap(int* a, int* b) {


int t = *a;
*a = *b;
*b = t;
}

int partition(int arr[], int low, int high) {


int pivot = arr[high]; // Pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j < high; j++) {


// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++; // Increment index of smaller element
swap(&arr[i], &arr[j]);
}
}

swap(&arr[i + 1], &arr[high]);


return (i + 1);
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


printArray(arr, n);

quickSort(arr, 0, n - 1);

printf("Sorted array: ");


printArray(arr, n);
return 0;
}

RESULT : Thus the program for sorting using insertion sort, merge sort and quick sort was
executed and the output is verified

You might also like