Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

algorithm lab record IV sem 2021 reg (1)

The document outlines the course structure for CS3401 - Algorithms, detailing course outcomes, educational objectives, and program outcomes for students in the Computer Science and Engineering department for the academic year 2024-2025. It includes a list of experiments related to algorithm implementation and analysis, along with guidelines for laboratory conduct. Additionally, it emphasizes the department's vision and mission to provide skill-based technical education and produce employable graduates.

Uploaded by

Amudaria
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

algorithm lab record IV sem 2021 reg (1)

The document outlines the course structure for CS3401 - Algorithms, detailing course outcomes, educational objectives, and program outcomes for students in the Computer Science and Engineering department for the academic year 2024-2025. It includes a list of experiments related to algorithm implementation and analysis, along with guidelines for laboratory conduct. Additionally, it emphasizes the department's vision and mission to provide skill-based technical education and produce employable graduates.

Uploaded by

Amudaria
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 76

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS3401-ALGORITHMS

NAME :

REG NO :

SEM :

YEAR :

1
Department of Computer Science and Engineering

CS3401-ALGORITHMS

2024-2025

This is to certify that this is a bonafide record of the work done by Ms.

……………………………………………………….Register Number….…………………………..in

the………………………………………………………..Course in the………….. Semester.

Staff-in-Charge Head of the Department

Submitted for the University Examination held on ………………………………………

Internal Examiner External Examiner

2
Subject Code & Name : CS3401 - Algorithms

Branch : CSE
Year/Semester : II/IV
Course Outcomes :
On the successful completion of the course, the students will be able to

Cos Knowledge Course Outcomes


Level
CO1 K3 Analyze the efficiency of algorithms using various frameworks.
CO2 K3 Apply graph algorithms to solve problems and analyze their
efficiency.
CO3 K3 Make use of algorithm design techniques like divide and conquer,
dynamic programming and greedy techniques to solve problems.
CO4 K3 Use the state space tree method for solving problems.
CO5 K4 Solve problems using approximation algorithms and randomized
algorithms.

3
COLLEGE VISION & MISSION STATEMENT
Vision
To incubate value based technical education and produce outstanding women graduate to compete
with the technological challenges with right attitude towards social empowerment.
Mission
 To equip necessary resources and to establish sufficient infrastructure for a beneficial process of learning that
paves the way for making ideal technocrats.
 To educate and make the students efficient with necessary skills and to make them industry ready engineers.
 To establish high-level learning and research skills to confront technological scenarios.
 To provide valuable resources for social empowerment and lifelong learning process.
DEPARTMENT VISION & MISSION STATEMENT
Vision
To provide skill based technical education in the field of Computer Science with evolving technologies and to
produce employable individuals in the society.
Mission
 To create an environment for student-centric learning and impart quality technical education for professionals.
 To provide training in latest technological trends and advancements in the world of computing technology.
 To empower the students with required skills to solve the complex technical problems.
 To enhance the creativity in research and to develop the competency of the students in technological field.
PROGRAM EDUCATIONAL OBJECTIVES (PEO’s)
 To direct the students in analytical, design and implementation skills for solving computational problems.
 To train the students to become a software professional with social responsibilities and ethical values.
 To enable the graduates be effective team member and infuse leadership qualities.
PROGRAM OUTCOMES (PO'S)
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems 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.

4
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage:
Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools including
prediction and modeling to complex engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the 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.
11. Project management and finance: Demonstrate knowledge and understanding of the 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.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PROGRAM SPECIFIC OUTCOMES PROGRAM (PSO’S)
 Able to solve problems in the broad area of programming concepts, appraise environmental and social
issues with ethics and manage different projects.
 Apply the acquired knowledge to design and develop the computer software and hardware.
 Create solutions by adapting emerging technologies for real time applications of industry.

5
LIST OF EXPERIMENTS WITH COs, POs & PSOs

S.No NAME OF EXPERIMENTS COs POs PSOs


Implement Linear Search. Determine the time CO1 1,2,3,4,9,10,11,12 1,2,3
required to search for an element. Repeat the
1 experiment for different values of n, the number
of elements in the list to be searched and plot a
graph of the time taken versus n.
Implement recursive Binary Search. Determine CO1 1,2,3,4,9,10,11,12 1,2,3
the time required to search an element. Repeat
2 the experiment for different values of n, the
number of elements in the list to be searched
and plot a graph of the time taken versus n.
Given a text txt [0...n-1] and a pattern pat CO1 1,2,3,4,9,10,11,12 1,2,3
[0...m-1], write a function search
3 (char pat [ ], char txt [ ]) that prints all
occurrences of pat [ ] in txt [ ].You may assume
that n > m.
Sort a given set of elements using the Insertion CO2 1,2,3,4,9,10,11,12 1,2,3
sort and Heap sort methods and determine the
time required to sort the elements. Repeat
4
the experiment for different values of n, the
number of elements in the list to be sorted and
plot a graph of the time taken versus n.
Develop a program to implement graph CO2 1,2,3,4,9,10,11,12 1,2,3
5
traversal using Breadth First Search
Develop a program to implement graph traversal CO3 1,2,3,4,9,10,11,12 1,2,3
6
using Depth First Search
From a given vertex in a weighted connected CO3 1,2,3,4,9,10,11,12 1,2,3
graph, develop a program to find the shortest
7
paths to other vertices using Dijkstra’s
algorithm.
Find the minimum cost spanning tree of a CO3 1,2,3,4,9,10,11,12 1,2,3
8
given undirected graph using Prim’s algorithm.
Implement Floyd’s algorithm for the All-Pairs- CO4 1,2,3,4,9,10,11,12 1,2,3
9
Shortest-Paths problem.
Compute the transitive closure of a given CO4 1,2,3,4,9,10,11,12 1,2,3
10
directed graph using Warshall's algorithm.
Develop a program to find out the maximum CO5 1,2,3,4,5,9,10,11, 1,2,3
and minimum numbers in a given list of n 12
11
numbers using the divide and conquer
technique.
Implement Merge sort and Quick sort methods CO5 1,2,3,4,5,9,10,11, 1,2,3
to sort an array of elements and determine the 12
time required to sort. Repeat the experiment for
12 different values of n, the number of elements in
the list to be sorted and plot a graph of the time
taken versus n.

6
Implement N Queens problem using CO5 1,2,3,4,5,9,10,11, 1,2,3
13
Backtracking. 12
Implement any scheme to find the optimal CO4 1,2,3,4,9,10,11,12 1,2,3
solution for the Traveling
Salesperson problem and then solve the same
14
problem instance using any approximation
algorithm and determine the error in the
approximation.
Implement randomized algorithms for finding CO4 1,2,3,4,9,10,11,12 1,2,3
15
the kth smallest number.
ADDITIONAL EXPERIMENTS
1,2,3,4,6,7,8,9,10,11,
16 Implemenet a Program to find solution for job CO4 12 1,2,3
sequencing with Deadlines Problem
Implement a program for Hamiltonian circuit CO4 1,2,3,4,8,9,10,11,12 1,2,3
17
Problem
18 Develop a program for Subset Sum Problem CO3 1,2,3,4,6,9,10,11,12 1,2,3

19 Develop a program for Solving 15-Puzzle problem CO1 1,2,3,4,7,9,10,11,12 1,2,3

7
Instructions to Students
DOs:
 Always sit on assigned computer.
 Enter laboratory in time and work quitely.
 Use the computer properly to keep it in good working condition.
 Wear id cards and lab coats before entering the laboratory.
 Report the problems identifies in the computer to the staff in charge.
 Shut down the computer properly before leaving the lab.

DON’Ts:
 Do not eat in the lab.
 D not wander around the room and distract other students.
 Do not remove anything from the computer laboratory without permission.
 Avoid stepping on electrical wires or any other computer cables
 Do not change the computer settings.
 Unauthorized access to any software is prohibited.
 Do not connect pen drive or any other storing devices.
 Do not download any software from unauthorized sites.
 Do not send any emails to unauthorized persons without permission.

8
INDEX

Ex.No Date Name of the Experiment Mark Signature


Implement Linear Search. Determine the time required to search
1. for an element. Repeat the experiment for different values of n,
the number of elements in the list to be searched and plot a graph
of the time taken versus n.
Implement recursive Binary Search. Determine the time required
2. to search an element. Repeat the experiment for different values
of n, the number of elements in the list to be searched and plot a
graph of the time taken versus n.
Given a text txt [0...n-1] and a pattern pat [0...m-1], write a
3. function search
(char pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in
txt [ ].You may assume that n > m.
Sort a given set of elements using the Insertion sort and Heap
4. sort methods and determine the time required to sort the
elements. Repeat the
experiment for different values of n, the number of elements in
the list to be sorted and plot a graph of the time taken versus n.
5. Develop a program to implement graph traversal using Breadth
First Search
6. Develop a program to implement graph traversal using Depth
First Search
7. From a given vertex in a weighted connected graph, develop a
program to find the shortest paths to other vertices using
Dijkstra’s algorithm.
8. Find the minimum cost spanning tree of a given undirected
graph using Prim’s algorithm.

9. Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths


problem.
10. Compute the transitive closure of a given directed graph using
Warshall's algorithm.
11. Develop a program to find out the maximum and minimum
numbers in a given list of n numbers using the divide and conquer
technique.
Implement Merge sort and Quick sort methods to sort an array of
12. elements and determine the time required to sort. Repeat the
experiment for different values of n, the number of elements in
the list to be sorted and plot a graph of the time taken versus n.

13 Implement N Queens problem using Backtracking.

Implement any scheme to find the optimal solution for the


14 Traveling
Salesperson problem and then solve the same problem instance
using any approximation algorithm and determine the error in the
approximation.
9
15 Implement randomized algorithms for finding the kth smallest
number.
Additional Experiments
16 Implemenet a Program to find solution for job sequencing with
Deadlines Problem
17 Implement a program for Hamiltonian circuit
Problem
18 Develop a program for Subset Sum Problem

19 Develop a program for Solving 15-Puzzle problem

10
Ex. No. 1 LINEAR SEARCH
Date:

Aim
To Implement Linear Search and calculate the time required to search for
an element.

Algorithm

1. Step 1: set pos = -1


2. Step 2: set i = 1
3. Step 3: repeat step 4 while i <= n
4. Step 4: if a[i] == val
5. set pos = i
6. print pos
7. go to step 6
8. [end of if]
9. set i = i + 1
10. [end of loop]
11. Step 5: if pos = -1
12. print "value is not present in the array "
13. [end of if]
14. Step 6: exit

11
Program
/ Online C compiler to run C program online
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define max 20 int
pos;
int linsearch (int,int[],int);
void main()
{ int ch=1; double t; int n,i,a [max],k,op,low,high,pos;
clock_t begin,end,ctime;
double cpu_time_used;
begin=clock();
end=clock(); while(ch)

{
printf("\n.......MENU. ..... \n 1.Linear search \n 2.Exit \n");
printf("\n enter your choice\n");
scanf("%d",&op);
switch(op)
{
case 1:printf("\n enter the number of elements \n");
scanf("%d",&n);
printf("\n enter the elements of an array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n enter the element to be searched \n");
scanf("%d",&k);
begin=clock();
pos=linsearch(n,a,k);
end=clock();
if(pos==-1)
printf("\n\n Unsuccessful search");
else
printf("element %d is found at position %d",k,pos+1);
ctime=(end-begin)/cpu_time_used;
printf("\n Time taken is %ld CPU cycles \n",ctime);
break;

default:printf("Invalid choice entered \n");


exit(0);
}
printf("\n Do you wish to run again(1/0) \n");
scanf("%d",&ch);
}
}
int linsearch(int n,int a[],int k)

12
{
if(n<0) return -1;
if(k==a[n-1])
return (n-1);
else
return linsearch(n-1,a,k);
}

Sample output:

Result
Thus the program to execute the linear Search was executed successfully.

13
EX NO: 2 RECCURSIVE BINARY SEARCH
DATE:

AIM:
To Implement the recursive binary search and calculate the CPU running
time of the algorithm.

ALGORITHM
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half
subarray after the mid element. So we recur for right half.
4. Else (x is smaller) recur for the left half.

PROGRAM CODE:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define max 20
int pos;
int binsearch (int,int[],int,int,int);
int linsearch (int,int[],int);
void main()
{ int ch=1; double t; int n,i,a
[max],k,op,low,high,pos; long tick1,tick2;
long elapsed=tick2-tick1;
double elapsed_time =
((double)elapsed/CLOCKS_PER_SEC); while(ch)
{
printf("\n.......MENU. ..... \n 1.BinarySearch \n 2.Linear search \n 3.Exit \
n"); printf("\n enter your choice\n");
scanf("%d",&op);
switch(op)
{
case 1:printf("\n enter the number of elments\n"); scanf("%d",&n);
printf("\n enter the number of an array in the order \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n enter the elements to be searched \
n"); scanf("%d",&k); low=0;high=n-1;
tick1=clock(); pos=binsearch(n,a,k,low,high);
tick2=clock();

if(pos==-1) printf("\n\
nUnsuccessful search"); else

14
printf("\n element %d is found at position %d",k,pos+1);
printf("Time taken by the CPU is %lf seconds \
n",elapsed_time); break;
case 2:printf("\n enter the number of elements \
n"); scanf("%d",&n);
printf("\n enter the elements of an array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n enter the element to be searched \n");
scanf("%d",&k);
tick1=clock();
pos=linsearch(n,a,k);
tick2=clock();
if(pos==-1)
printf("\n\n Unsuccessful search");
else
printf("element %d is found at position %d",k,pos+1);
printf("Time taken by the CPU is %lf seconds \
n",elapsed_time); break;
default:printf("Invalid choice entered \n");
exit(0);
}
printf("\n Do you wish to run again(1/0) \n");
scanf("%d",&ch);
}
}
int binsearch(int n,int a[],int k,int low,int high)
{
int mid;
mid=(low+high)/2;
if(low>high)
return -1;
if(k==a[mid])
return(mid);
else
if(k<a[mid])
return binsearch(n,a,k,low,mid-1);
else
return binsearch(n,a,k,mid+1,high);
}
int linsearch(int n,int a[],int k)
{
if(n<0) return -1;
if(k==a[n-1])
return (n-1);
else
return linsearch(n-1,a,k);
}

15
SAMPLE OUTPUT

RESULT
Thus the program to implement the recursive binary search was executed
successfully.

16
EX NO: 3 NAIVE PATTERN SEARCH
DATE:

AIM:
To perform Given a text txt [0...n-1] and a pattern pat [0...m-1], write a
function search (char pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in txt [ ].

ALGORITHM
1. n ← length [T]
2. m ← length [P]
3. for s ← 0 to n -m
4. do if P [1.....m] = T [s + 1 ... s + m]
5. then print "Pattern occurs with shift"

PROGRAM CODE:

#include <stdio.h>
#include <string.h>
void search(char* pat, char* txt)
{int M = strlen(pat);
int N = strlen(txt);
for (int i = 0; i <= N - M; i++)
{int j;for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j == M)
printf("Pattern found at index %d \n", i);

}}
int main()
{char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
search(pat, txt);
return 0;
}

17
SAMPLE OUTPUT

Result
Thus the naive pattern matching algorithm was implemented successfully

18
EX NO :4a INSERTION SORT
DATE:

AIM
To Sort a given set of elements using the Insertion sort method and determine the
time required to sort the elements.

ALGORITHM
1. Iterate from arr[1] to arr[N] over the array.
2. Compare the current element (key) to its predecessor.
3. If the key element is smaller than its predecessor, compare it to the elements
before. Move the greater elements one position up to make space for the
swapped element.

PROGRAM
#include <math.h>
#include <stdio.h>
#include <time.h>
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n) {

sleep(4);
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)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{

19
long tick1,tick2;
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
tick1 = clock();
insertionSort(arr, n);
tick2 = clock();
long elapsed = tick2-tick1;
double elapsed_time = ((double)elapsed/CLOCKS_PER_SEC);
printArray(arr, n);
printf("Time taken by the CPU is %lf seconds \
n",elapsed_time); return 0;
}

SAMPLE OUTPUT

RESULT
Thus the program to Sort a given set of elements using the Insertion sort method
and determine the time required to sort the elements

20
EX NO :4b HEAP SORT
DATE:

AIM
To Sort a given set of elements using the Heap sort method and determine the
time required to sort the elements.

ALGORITHM

1. First convert the array into heap data structure using heapify, then one by one delete
the root node of the Max-heap and replace it with the last node in the heap and then
heapify the root of the heap. Repeat this process until size of heap is greater than 1.
2. Build a heap from the given input array.
3. Repeat the following steps until the heap contains only one element:
a. Swap the root element of the heap (which is the largest
element) with the last element of the heap
b. Remove the last element of the heap (which is now in the
correct position).
c. Heapify the remaining elements of the heap.
4. The sorted array is obtained by reversing the order of the elements in the input
array.

PROGRAM
#include <stdio.h>
#include<time.h>

void main()
{
int heap[10], num, i, j, c, rootElement,
tempVar; long tick1,tick2;

printf("\n Enter num of elements :");


scanf("%d", &num);
printf("\n Enter the nums : ");
for (i = 0; i < num; i++)
scanf("%d", &heap[i]);
for (i = 1; i < num; i++)
{
c = i;
do
{
rootElement = (c - 1) / 2;
if (heap[rootElement] < heap[c]) /* to create MAX heap array */

21
{
tempVar = heap[rootElement];
heap[rootElement] = heap[c];
heap[c] = tempVar;
}
c = rootElement;
} while (c != 0);
}
tick1=clock();
printf("Heap array : ");
for (i = 0; i < num; i++)
printf("%d\t ", heap[i]);
for (j = num - 1; j >= 0; j--)
{
tempVar = heap[0];
heap[0] = heap[j];
heap[j] = tempVar;
rootElement = 0;
do
{
c = 2 * rootElement + 1;
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[rootElement]<heap[c] && c<j)
{ tempVar = heap[rootElement];
heap[rootElement] = heap[c];

heap[c] = tempVar;
}
rootElement = c;
} while (c < j);
}
printf("\n The sorted array is : ");
for (i = 0; i < num; i++)
printf("\t %d", heap[i]);
tick2-clock();
long elapsed = tick2-tick1;
double elapsed_time = ((double)elapsed/CLOCKS_PER_SEC);
printf("Time taken by the CPU is %lf seconds \n",elapsed_time);

22
SAMPLE OUTPUT

RESULT
Thus the program to implement heap sort was executed successfully

23
EX NO :5 BREADTH FIRST SEARCH
DATE:

AIM
To Develop a program to implement graph traversal using Breadth First Search

ALGORITHM
1. Start by putting any one of the graph's vertices at the back of a queue.

2. Take the front item of the queue and add it to the visited list.

3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited
list to the back of the queue.

4. Keep repeating steps 2 and 3 until the queue is empty.

PROGRAM

#include <stdio.h>
#include <stdlib.h>
#define SIZE 40

struct queue {
int items[SIZE];
int front;
int rear;
};

struct queue* createQueue();


void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);

struct node {
int vertex;
struct node* next;
};

struct node* createNode(int);

struct Graph {
int numVertices;

24
struct node** adjLists;
int* visited;
};

// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();

graph->visited[startVertex] = 1;
enqueue(q, startVertex);

while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);

struct node* temp = graph->adjLists[currentVertex];

while (temp) {
int adjVertex = temp->vertex;

if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}

// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Creating a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct
Graph)); graph->numVertices = 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;

25
}

return graph;
}

// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

/ Add edge from dest to src newNode =


createNode(src); newNode->next =
graph->adjLists[dest]; graph-
>adjLists[dest] = newNode;
}

// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}

/ Check if the queue is empty


int isEmpty(struct queue* q) {
if (q->rear == -1)
return
1; else
return 0;
}

/ Adding elements into queue


void enqueue(struct queue* q, int value) {
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q- >rear++;
q->items[q->rear] = value;
}
}

/ Removing elements from queue


int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) {

26
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}

// Print the queue


void printQueue(struct queue* q) {
int i = q->front;

if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}

int main() {
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);

bfs(graph, 0);

return 0;
}

27
SAMPLE OUTPUT

RESULT

Thus the program to implement the breadth first search was executed successfully.

28
EX NO :6 DEPTH FIRST SEARCH
DATE:

AIM
To Implement the Graph traversal using depth first search.

ALGORITHM

1. Start by putting any one of the graph's vertices on top of a stack.


2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the
visited list to the top of the stack.
4. Keep repeating steps 2 and 3 until the stack is empty.

PROGRAM

#include <stdio.h>
#include <stdlib.h>
/ Globally declared visited
array int vis[100];
/ Graph structure to store number
/ of vertices and edges and
/ Adjacency matrix
struct Graph {
int V;
int E;
int** Adj;
};
/ Function to input data of graph
struct Graph* adjMatrix()
{
struct Graph* G = (struct Graph*)
malloc(sizeof(struct Graph));
if (!G) {
printf("Memory Error\n");
return NULL;
}
G->V = 7;
G->E = 7;

G->Adj = (int**)malloc((G->V) *
sizeof(int*)); for (int k = 0; k < G->V; k++) {
G->Adj[k] = (int*)malloc((G->V) * sizeof(int));
}

29
for (int u = 0; u < G->V; u++) {
for (int v = 0; v < G->V; v++) {
G->Adj[u][v] = 0;
}
}
G->Adj[0][1] = G->Adj[1][0] = 1;
G->Adj[0][2] = G->Adj[2][0] = 3;
G->Adj[1][3] = G->Adj[3][1] = 1;
G->Adj[1][4] = G->Adj[4][1] = 4;
G->Adj[1][5] = G->Adj[5][1] = 1;
G->Adj[1][6] = G->Adj[6][1] = 6;
G->Adj[6][2] = G->Adj[2][6] = 1;

return G;
}// DFS function to print DFS traversal of
graph void DFS(struct Graph* G, int u)
{
vis[u] = 1;
printf("%d ", u);
for (int v = 0; v < G->V; v++) {
if (!vis[v] && G->Adj[u][v]) {
DFS(G, v);
}
}
}
// Function for DFS traversal
void DFStraversal(struct Graph* G)
{
for (int i = 0; i < 100; i++) {
vis[i] = 0;
}
for (int i = 0; i < G->V; i++) {
if (!vis[i]) {
DFS(G, i);
}}}
/ Driver code
void main()
{
struct Graph* G;
G = adjMatrix();
DFStraversal(G);
}

30
SAMPLE OUTPUT

RESULT

Thus the program to implement the graph traversal using depth first search
was completed successfully.

31
EX NO :7 DIJIKSTRA’S ALGORITHM
DATE:

AIM
To implement a program to find the shortest paths to other vertices using
Dijkstra’s algorithm.

ALGORITHM

1. Set all vertices distances = infinity except for the source vertex, set the
source distance = 0.
2. Push the source vertex in a min-priority queue in the form (distance , vertex), as
the comparison in the min-priority queue will be according to vertices distances.
3. Pop the vertex with the minimum distance from the priority queue (at first the
popped vertex = source).
4. Update the distances of the connected vertices to the popped vertex in case of
"current vertex distance + edge weight < next vertex distance", then push the vertex
with the new distance to the priority queue.
5. If the popped vertex is visited before, just continue without using it.
6. Apply the same algorithm again until the priority queue is empty.

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

/ Number of vertices in the graph


#define V 9

/ A utility function to find the vertex with minimum


/ distance value, from the set of vertices not yet included
/ in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

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


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}
void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");

32
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}

/ Function that implements Dijkstra's single source


/ shortest path algorithm for a graph represented using
/ adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the
/ shortest
/ distance from src to i

bool sptSet[V]; // sptSet[i] will be true if vertex i is


// included in shortest
/ path tree or shortest distance from src to i is
/ finalized

/ Initialize all distances as INFINITE and stpSet[] as


/ false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;

/ Distance of source vertex from itself is always


0 dist[src] = 0;

/ Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);

/ Mark the picked vertex as


processed sptSet[u] = true;

/ Update dist value of the adjacent vertices of the


/ picked vertex.
for (int v = 0; v < V; v++)

/ Update dist[v] only if is not in sptSet,


/ there is an edge from u to v, and total
/ weight of path from src to v through u is
/ smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v]
& dist[u] != INT_MAX
& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

/ print the constructed distance


array printSolution(dist);
}

33
/ driver's
code int
main()
{
/* Let us create the example graph discussed above
*/ int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{4,0,8,0,0,0,0,11,0},
{0,8,0,7,0,4,0,0,2},
{0,0,7,0,9,14,0,0,0},
{0,0,0,9,0,10,0,0,0}, { 0, 0,
4, 14, 10, 0, 2, 0, 0 },
{0,0,0,0,0,2,0,1,6},
{8,11,0,0,0,0,1,0,7},
{0,0,2,0,0,0,6,7,0}};

/ Function call
dijkstra(graph, 0);

return 0;
}
SAMPLE OUTPUT

RESULT

Thus the program to implement the shortest paths to other vertices using
Dijkstra’s algorithm was executed successfully.

34
EX NO :8 PRIM’S ALGORITHM
DATE:

AIM
To implement the minimum cost spanning tree of a given undirected graph
using Prim’s algorithm.

ALGORITHM
Step 1: Determine an arbitrary vertex as the starting vertex of the MST.
Step 2: Follow steps 3 to 5 till there are vertices that are not included in the
MST (known as fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
Step 6: Return the MST and exit

PROGRAM

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 5
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;
}

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

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

35
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},

36
{0,5,7,9,0}};

/ Print the solution


primMST(graph);

return 0;
}

SAMPLE OUTPUT

RESULT

This the program to implement the minimum cost spanning tree of a given undirected
graph using Prim’s algorithm.

37
EX NO :9 FLOYD’S ALGORITHM
DATE:

AIM
To implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem
ALGORITHM:

1. Initialize the solution matrix same as the input graph matrix as a first step.
2. Then update the solution matrix by considering all vertices as an intermediate
vertex.
3. The idea is to one by one pick all vertices and updates all shortest paths which
include the picked vertex as an intermediate vertex in the shortest path.
4. When we pick vertex number k as an intermediate vertex, we already have
considered vertices {0, 1, 2, .. k-1} as intermediate vertices.
5. For every pair (i, j) of the source and destination vertices respectively, there are two
possible cases.
o k is not an intermediate vertex in shortest path from i to j. We keep
the value of dist[i][j] as it is.
o k is an intermediate vertex in shortest path from i to j. We update the
value of dist[i][j] as dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] +
dist[k][j]

PROGRAM
/ C Program for Floyd Warshall
Algorithm #include <stdio.h>

/ Number of vertices in the graph


#define V 4

/* Define Infinite as a large enough


value. This value will be used
for vertices not connected to each other */
#define INF 99999

/ A function to print the solution


matrix void printSolution(int dist[][V]);

/ Solves the all-pairs shortest path


/ problem using Floyd Warshall algorithm
void floydWarshall(int dist[][V])
{
int i, j, k;

/* Add all vertices one by one to


the set of intermediate vertices.
---> Before start of an iteration, we
have shortest distances between all
pairs of vertices such that the shortest

38
distances consider only the
vertices in set {0, 1, 2, .. k-1} as
intermediate vertices.
----> After the end of an iteration,
vertex no. k is added to the set of
intermediate vertices and the set
becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++) {
/ Pick all vertices as source one by
one for (i = 0; i < V; i++) {
/ Pick all vertices as destination for the
/ above picked source
for (j = 0; j < V; j++) {
/ If vertex k is on the shortest path from
/ i to j, then update the value of
/ dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}

/ Print the shortest distance


matrix printSolution(dist);
}

/* A utility function to print solution */


void printSolution(int dist[][V])
{
printf(
"The following matrix shows the shortest distances"
" between every pair of vertices \
n"); for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) { if
(dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}

/ driver's code
int main()
{
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };

39
/ Function call
floydWarshall(graph);
return 0;
}
SAMPLE OUTPUT

RESULT

Thus the program to implement Floyd’s algorithm for the All-Pairs- Shortest-
Paths problem was executed successfully.

40
EX NO :10 WARSHALL’S ALGORITHM
DATE:

AIM
To implement the transitive closure of a given directed graph using
Warshall's algorithm

ALGORITHM

1. Warshall(A[1...n, 1...n]) // A is the adjacency matrix


2. R(0) ← A
3. for k ← 1 to n do
4. for i ← 1 to n do
5. for j ← to n do
6. R(k)[i, j] ← R(k-1)[i, j] or (R(k-1)[i, k] and R(k-1)[k, j])
7. return R(n)
PROGRAM

#include<stdio.h>
#include<math.h>
int max(int, int);
void warshal(int p[10][10], int n) {
int i, j, k;
for (k = 1; k <= n; k++)
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
p[i][j] = max(p[i][j], p[i][k] && p[k][j]);
}
int max(int a, int b) {
;
if (a > b)
return (a);
else
return (b);
}
void main() {
int p[10][10] = { 0 }, n, e, u, v, i, j;
printf("\n Enter the number of vertices:");
scanf("%d", &n);
printf("\n Enter the number of edges:");
scanf("%d", &e);
for (i = 1; i <= e; i++) {
printf("\n Enter the end vertices of edge %d:", i);
scanf("%d%d", &u, &v);
p[u][v] = 1;
}
printf("\n Matrix of input data: \n");

41
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf("%d\t", p[i][j]);
printf("\n");
}
warshal(p, n);
printf("\n Transitive closure: \n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf("%d\t", p[i][j]);
printf("\n");
}
}
SAMPLE OUTPUT

RESULT
Thus the transitive closure of a given directed graph using Warshall's
algorithm Was executed successfully.

42
EX NO :11 FINDING MAXIMUM AND MINIMUM NUMBERS IN A
ARRAY
DATE:

AIM
To implement a program to find out the maximum and minimum numbers in a
given list of n numbers using the divide and conquer technique.
ALGORITHM
1. Create two intermediate variables max and min to store the maximum and
minimum element of the array.
2. Assume the first array element as maximum and minimum both, say max =
arr[0] and min = arr[0].
3. Traverse the given array arr[].
4. If the current element is smaller than min, then update the min as the
current element.
5. If the current element is greater than the max, then update the max as the
current element.
6. Repeat the above two steps 4 and 5 for the element in the array.

PROGRAM

#include<stdio.h>
#include<stdio.h>
int max, min;
int a[100];
void maxmin(int i, int j)
{
int max1, min1, mid;
if(i==j)
{
max = min = a[i];
}
else
{
if(i == j-1)
{
if(a[i] <a[j])
{
max = a[j];
min = a[i];
}
else
{
max = a[i];
min = a[j];
}
}
else

43
{
mid = (i+j)/2;
maxmin(i, mid);
max1 = max; min1 = min;
maxmin(mid+1, j);
if(max <max1)
max = max1;
if(min > min1)
min = min1;
} }}
int main ()
{
int i, num;
printf ("\nEnter the total number of numbers :
"); scanf ("%d",&num);
printf ("Enter the numbers : \n");
for (i=1;i<=num;i++)
scanf ("%d",&a[i]);
max = a[0];
min = a[0];
maxmin(1, num);
printf ("Minimum element in an array : %d\n", min);
printf ("Maximum element in an array : %d\n",
max); return 0;
}
SAMPLE OUTPUT

RESULT
Thus the program to find out the maximum and minimum numbers in a given list of
n numbers using the divide and conquer technique was executed successfully.

44
EX NO :12A MERGE SORT
DATE:

AIM
To Implement merge sort methods to sort an array of elements and determine the
time required to sort.

ALGORITHM
step 1: start
step 2: declare array and left, right, mid variable
step 3: perform merge function.
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
step 4: Stop
PROGRAM
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

/ Merges two subarrays of arr[].


/ First subarray is arr[l..m]
/ Second subarray is
arr[m+1..r] void merge(int arr[],
int l,
int m, int r)
{
int i, j, k;
int n1 = m - l +
1; int n2 = r - m;

/ Create temp arrays


int L[n1], R[n2];

/ Copy data to temp 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]
/ Initial index of first subarray

45
i = 0;

/ Initial index of second subarray


j = 0;

/ Initial index of merged


subarray 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 there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

/ Copy the remaining elements of


/ R[], if there are any
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

/ l is for left index and r is


/ right index of the sub-array
/ of arr to be sorted
void mergeSort(int arr[],
int l, int r)
{
if (l < r)
{
/ Same as (l+r)/2, but avoids
/ overflow for large l and h

46
int m = l + (r - l) / 2;

/ Sort first and second


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

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

/ UTILITY FUNCTIONS
/ Function to print an array void
printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

/ Driver code
int main()
{
long tick1,tick2;
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);
tick1=clock();
mergeSort(arr, 0, arr_size - 1);
tick2=clock();
long elapsed=tick2-tick1;
printf("\nSorted array is \n");
double elapsed_time = ((double)elapsed/CLOCKS_PER_SEC);

printArray(arr, arr_size);
printf("Time taken by the CPU is %lf seconds \
n",elapsed_time); return 0;
}

47
SAMPLE OUTPUT

RESULT
Thus to Implement merge sort methods to sort an array of elements and determine
the time required to sort was executed successfully.

48
EX NO :12B QUICK SORT
DATE:

AIM
To Implement Quick sort methods to sort an array of elements and determine the
time required to sort.

ALGORITHM
Step 1 − Pick an element from an array, call it as pivot element.
Step 2 − Divide an unsorted array element into two arrays.
Step 3 − If the value less than pivot element come under first sub array, the
remaining elements with value greater than pivot come in second sub array.

PROGRAM

#include<stdio.h>
#include <time.h>
void quicksort(int number[25],int first,int last)
{ int i, j, pivot, temp;
sleep(10);
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];
long tick1,tick2;

49
printf("How many elements are u going to enter?:
"); scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
tick1=clock();
quicksort(number,0,count-1);
tick2=clock();
long elapsed =tick2-tick1;
double elapsed_time = ((double)elapsed/CLOCKS_PER_SEC);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
printf("Time taken by the CPU is %lf seconds \
n",elapsed_time); return 0;
}

SAMPLE OUTPUT

RESULT
Thus to Implement Quick sort methods to sort an array of elements and determine
the time required to sort was executed successfully.

50
EX NO: 13 N-QUEENS PROBLEM
DATE:

AIM
To Implement N Queens problem using Backtracking

ALGORITHM
1. Initialize an empty chessboard of size NxN.
2. Start with the leftmost column and place a queen in the first row of that column.
3. Move to the next column and place a queen in the first row of that column.
4. Repeat step 3 until either all N queens have been placed or it is impossible to place a
queen in the current column without violating the rules of the problem.
5. If all N queens have been placed, print the solution.
6. If it is not possible to place a queen in the current column without violating the rules
of the problem, backtrack to the previous column.
7. Remove the queen from the previous column and move it down one row.
8. Repeat steps 4-7 until all possible configurations have been tried.

PROGRAM

#define N 4
#include <stdbool.h>
#include <stdio.h>

void printSolution(int board[N][N])


{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
}
}

bool isSafe(int board[N][N], int row, int col)


{
int i, j;

/* Check this row on left side */


for (i = 0; i < col; i++)
if (board[row][i])
return false;

/* Check upper diagonal on left side */


for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;

/* Check lower diagonal on left side */

51
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;

return true;
}

/* A recursive utility function to solve N


Queen problem */
bool solveNQUtil(int board[N][N], int col)
{
/* base case: If all queens are placed
then return true */
if (col >= N)
return true;

/* Consider this column and try placing


this queen in all rows one by one */
for (int i = 0; i < N; i++) {
/* Check if the queen can be placed on
board[i][col] */
if (isSafe(board, i, col)) {
/* Place this queen in board[i][col] */
board[i][col] = 1;

/* recur to place rest of the queens */


if (solveNQUtil(board, col + 1))
return true;

/* If placing queen in board[i][col]


doesn't lead to a solution, then
remove queen from board[i][col] */
board[i][col] = 0; // BACKTRACK
}
}

/* If the queen cannot be placed in any row in


this column col then return false */
return false;
}

bool solveNQ( )
{
int board[N][N] = { { 0, 0, 0, 0 },
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}};

if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");

52
return false;
}

printSolution(board);
return true;
}

/ driver program to test above


function int main()
{
solveNQ()
; return 0;
}

SAMPLE OUTPUT

RESULT
Thus to Implement N Queens problem using Backtracking was executed successfully.

53
EX NO: 14 TRAVELLING SALESPERSON PROBLEM
DATE:

AIM
To find the optimal solution for the Traveling Salesperson problem and then solve
the same problem instance using any approximation algorithm and determine the error in the
approximation.

ALGORITHM
1. Start on an arbitrary vertex as current vertex.
2. Find out the shortest edge connecting current vertex and an unvisited vertex V.
3. Set current vertex to V.
4. Mark V as visited.
5. If all the vertices in domain are visited, then terminate.
6. Go to step 2.
7. The sequence of the visited vertices is the output of the algorithm.

PROGRAM

#include<stdio.h>
int a[10][10],n,visit[10];
int cost_opt=0,cost_apr=0;
int least_apr(int c);
int least_opt(int c);

void mincost_opt(int city)


{
int i,ncity;
visit[city]=1;
printf("%d-->",city);
ncity=least_opt(city);
if(ncity==999)
{
ncity=1;
printf("%d",ncity);
cost_opt+=a[city][ncity];
return;
}
mincost_opt(ncity);
}
void mincost_apr(int city)
{
int i,ncity;
visit[city]=1;
printf("%d-->",city);
ncity=least_apr(city);
if(ncity==999)
{

54
ncity=1;
printf("%d",ncity);
cost_apr+=a[city][ncity];
return;
}
mincost_apr(ncity);
}

int least_opt(int c)
{
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
{
if((a[c][i]!=0)&&(visit[i]==0))
if(a[c][i]<min)
{
min=a[i][1]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost_opt+=kmin;
return nc;
}

int least_apr(int c)
{
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
{
if((a[c][i]!=0)&&(visit[i]==0))
if(a[c][i]<kmin)
{
min=a[i][1]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost_apr+=kmin;
return nc;
}
void main()
{
int i,j;
printf("Enter No. of cities:\n");
scanf("%d",&n);

55
printf("Enter the cost matrix\n");
for(i=1;i<=n;i++)
{
printf("Enter elements of row:%d\n",i );
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
visit[i]=0;
}
printf("The cost list is \n");
for(i=1;i<=n;i++)
{
printf("\n\n");
for(j=1;j<=n;j++)
printf("\t%d",a[i][j]);
}
printf("\n\n Optimal Solution :\n");
printf("\n The path is :\n");
mincost_opt(1);
printf("\n Minimum cost:");
printf("%d",cost_opt);

printf("\n\n Approximated Solution :\n");


for(i=1;i<=n;i++)
visit[i]=0;
printf("\n The path is :\n");
mincost_apr(1);
printf("\nMinimum cost:");
printf("%d",cost_apr);
printf("\n\nError in approximation is approximated solution/optimal solution=
%f", (float)cost_apr/cost_opt);
}

56
SAMPLE OUTPUT

RESULT
Thus the optimal solution for the Traveling Salesperson problem and then solve
the same problem instance using any approximation algorithm and determine the error in
the approximation.

57
EX NO: 15 FINDING THE Kth SMALLEST NUMBER
DATE:

AIM
To implement randomized algorithms for finding the kth smallest number.

ALGORITHM
1. check if k>0&& k<=r-l+1:

 declare pos as randomPartition(arr,l,r).


 check if pos-1==k-1 than return arr[pos].
 check if pos-1>k-1 than recursively call kthsmallest(arr,l,pos-1,k).
 return recursively call kthsmallest(arr,pos+1,r,k-pos+l-1).
2. return INT_MAX.
PROGRAM

#include<iostream>
#include<climits>
#include<cstdlib>
using namespace std;

int randomPartition(int arr[], int l, int r);

/ This function returns k'th smallest element in arr[l..r] using


/ QuickSort based method. ASSUMPTION: ELEMENTS IN ARR[] ARE
DISTINCT int kthSmallest(int arr[], int l, int r, int k)
{
/ If k is smaller than number of elements in array
if (k > 0 && k <= r - l + 1)
{
/ Partition the array around a random element and
/ get position of pivot element in sorted array
int pos = randomPartition(arr, l, r);

/ If position is same as
k if (pos-l == k-1)
return arr[pos];
if (pos-l > k-1) // If position is more, recur for left
subarray return kthSmallest(arr, l, pos-1, k);

/ Else recur for right subarray


return kthSmallest(arr, pos+1, r, k-pos+l-1);
}

/ If k is more than the number of elements in the


array return INT_MAX;

58
}

void swap(int *a, int *b)


{
int temp = *a;
*a = *b;
*b = temp;
}

/ Standard partition process of QuickSort(). It considers the last


/ element as pivot and moves all smaller element to left of it and
/ greater elements to right. This function is used by
randomPartition() int partition(int arr[], int l, int r)
{
int x = arr[r], i = l;
for (int j = l; j <= r - 1; j++)
{
if (arr[j] <= x)
{
swap(&arr[i], &arr[j]);
i++;
}
}
swap(&arr[i], &arr[r]);
return i;
}

/ Picks a random pivot element between l and r and partitions


/ arr[l..r] around the randomly picked element using
partition() int randomPartition(int arr[ ], int l, int r)
{
int n = r-l+1;
int pivot = rand( ) % n;
swap(&arr[l + pivot], &arr[r]);
return partition(arr, l, r);
}

/ Driver program to test above methods


int main( )
{
int arr[] = {12, 3, 5, 7, 4, 19, 26};
int n = sizeof(arr)/sizeof(arr[0]), k = 3;
cout << "K'th smallest element is " << kthSmallest(arr, 0, n-1, k);
return 0;
}

59
SAMPLE OUTPUT

RESULT
th
Thus the program to implement randomized algorithms for finding the k smallest
number was executed successfully.

60
EX NO: 16 FIND SOLUTION FOR JOB SEQUENCING WITH
DEADLINES PROBLEM
DATE:

AIM
To find solution for job sequencing with deadlines problem.

ALGORITHM
1. Find the maximum deadline value from the input set of jobs.
2. Once, the deadline is decided, arrange the jobs in descending order of their profits.
3. Selects the jobs with highest profits, their time periods not exceeding the
maximum deadline.
4. The selected set of jobs are the output.
PROGRAM

#include<stdio.h>
#include<conio.h>
int jobseq();
void psort();
int tp,j[10],d[10],p[10],n;
void main()
{
int i,k;
clrscr();
printf("\n Enter the n'o of jobs:");
scanf("%d",&n);
printf("\n Enter the %d Deadlines for the
jobs:",n); for(i=1;i<=n;i++)
scanf("%d",&d[i]);
printf("\n Enter the Profits required for jobs:");
for(i=1;i<=n;i++)
scanf("%d",&p[i]);
psort();
for(i=1;i<n;i++)
printf("%d",p[i]);
k=jobseq();
printf("\n The Required Solution is:");
for(i=1;i<=k;i++)
{
tp=tp+p[j[i]];
printf("%d-->",j[i]);
}
printf("\n Profits:%d",tp);
getch();
}
int jobseq()
{
int i,k,q;
d[0]=0;

61
j[0]=0;
j[1]=1;
k=1;
for(i=2;i<=n;i++)
{
int r=k;
while((d[j[r]]>d[i]) && (d[j[r]]!=r))
r=r-1;
if((d[j[r]]<=d[i]) && (d[i]>r))
{
for(q=k;q>=r+1;q--)
{
j[q+1]=j[q];
}
j[r+1]=i;
k=k+1;
}
}
return k;
}
void psort()
{
int i,k,temp1;
for(i=1;i<=n;i++)
{
for(k=1;k<=n-i;k++)
{
if(p[k]<p[k+1])
{
temp1=p[k];
p[k]=p[k+1];
p[k+1]=temp1;
temp1=j[k];
j[k]=j[k+1];
j[k+1]=temp1;
temp1=d[k];
d[k]=d[k+1];
d[k+1]=temp1;
}
}
}
}

62
SAMPLE OUTPUT:

RESULT:

Thus the program to find solution for job sequencing with deadlines problem was
executed successfully.

63
EX NO: 17 Write a program for Hamiltonian circuit problem
DATE:

AIM
To write a program for Hamiltonian circuit problem.

ALGORITHM
1. Understand the Problem
Goal: Find a Hamiltonian circuit (cycle) in a given graph. A Hamiltonian circuit visits
each vertex exactly once and returns to the starting vertex.
Input: Adjacency matrix of the graph.
Output: A Hamiltonian circuit if it exists, otherwise indicate that no such circuit exists.
2. Define the Graph Representation
Use an adjacency matrix graph[V][V] where V is the number of vertices. An entry graph[i]
[j] is 1 if there is an edge between vertex i and vertex j, otherwise 0.
3. Initialize the Path
Create an array path[] of size V to store the Hamiltonian path. Initialize all entries to -1.
Set the starting vertex (typically 0) as the first vertex in the path: path[0] = 0.
4. Define Helper Functions
a. Check if Adding a Vertex is Safe
Function: isSafe(int graph[V][V], int path[], int pos, int v)
Purpose: To check whether the vertex v can be added at position pos in the path.
Check if the vertex v is adjacent to the previously added vertex (graph[path[pos - 1]][v] == 1).
Check if the vertex v is already included in the path to avoid cycles (path[i] == v for all i
< pos).
b. Recursive Function to Find Hamiltonian Circuit Function:
hamCycleUtil(int graph[V][V], int path[], int pos) Purpose:
To use backtracking to find the Hamiltonian cycle.
Base Case: If pos == V (all vertices are included in the path), check if there's an edge from
the last vertex in the path back to the starting vertex.
Recursive Case: Try adding each vertex v to the path and recursively check if the cycle can
be completed.
If adding vertex v doesn't lead to a solution, remove it (backtrack).
c. Print Solution
Function: printSolution(int path[])
Purpose: To print the Hamiltonian cycle if it exists. Include the starting vertex again at the
end to show it’s a cycle.
5. Solve the Problem

64
6.a. Start the Hamiltonian Cycle Search
Call the recursive function hamCycleUtil() starting from position 1, as vertex 0 is
already placed at position 0.
b. Output Results
If a Hamiltonian cycle is found, print it using printSolution().
If no cycle is found, indicate that no solution exists.
PROGRAM

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

#define V 5 // Number of vertices in the graph

// Function to check if the vertex v can be added at index 'pos' in the Hamiltonian
Cycle
bool isSafe(int graph[V][V], int path[], int pos, int v) {
/ Check if this vertex is an adjacent vertex of the previously added
vertex. if (graph[path[pos - 1]][v] == 0)
return false;

/ Check if the vertex has already been included.


for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;

return true;
}

/ Utility function to solve the Hamiltonian Cycle problem using


backtracking bool hamCycleUtil(int graph[V][V], int path[], int pos) {
/ Base case: If all vertices are included in the path
if (pos == V) {
/ And if there is an edge from the last included vertex to the first
vertex return (graph[path[pos - 1]][path[0]] == 1);
}

/ Try different vertices as the next candidate in the Hamiltonian


Cycle. for (int v = 1; v < V; v++) {
if (isSafe(graph, path, pos, v))
{ path[pos] = v;

/ Recur to construct the rest of the


path if (hamCycleUtil(graph, path, pos
+ 1))
return true;

/ If adding vertex v doesn't lead to a solution then remove


it path[pos] = -1;
}
}

65
return false;
}
/ Function to find and print the Hamiltonian
Cycle void printSolution(int path[]) {
printf("Solution Exists: Following is the Hamiltonian Cycle\
n"); for (int i = 0; i < V; i++)
printf("%d ", path[i]);
printf("%d\n", path[0]); // Print the starting vertex again to show it's a cycle
}

/ Function to solve the Hamiltonian Cycle problem


void hamCycle(int graph[V][V]) {
int path[V];

// Initialize the path


for (int i = 0; i < V; i++)
path[i] = -1;

/ Let the first vertex in the path be


0 path[0] = 0;

/ Try to complete the cycle


if (!hamCycleUtil(graph, path, 1)) {
printf("Solution does not exist\n");
return;
}

printSolution(path);
}

int main() {
/ Example graph
int graph[V][V] = {
{0, 1, 1, 1, 0},
{1, 0, 1, 0, 1},
{1, 1, 0, 1, 0},
{1, 0, 1, 0, 1},
{0, 1, 0, 1, 0}
};

printf("Input Graph (Adjacency Matrix):\n");


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
printf("%d ", graph[i][j]);
}
printf("\n");
}

hamCycle(graph);
return 0;
}

SAMPLE OUTPUT:

66
RESULT:

Thus the program to implement Hamiltonian circuit problem was


executed successfully.

67
EX NO: 18 Write a program for Subset Sum Problem
DATE:

AIM
To write a program for Subset Sum Problem .

ALGORITHM:

1. Initialize the DP Table:

2. Create a 2D boolean array dp[n+1][target+1] where n is the number of elements in


the set and target is the sum we want to check.
3. Initialize dp[i][0] to true for all i (a sum of 0 is always possible with an empty subset).
4. Initialize dp[0][j] to false for all j > 0 (no positive sum can be achieved with
0 elements).
5. Fill the DP Table:
6. Iterate over each element and each possible sum.
7. For each element set[i-1], update dp[i][j]:
8. If the current element set[i-1] is greater than j, then dp[i][j] is the same as dp[i-1]
[j] (exclude the element).
9. Otherwise, dp[i][j] is true if either dp[i-1][j] is true (excluding the element) or
dp[i-1][j - set[i-1]] is true (including the element).

PROGRAM:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

/ Function to check if there is a subset with sum equal to the


target bool isSubsetSum(int set[], int n, int target) {
/ Create a 2D array to store the results of subproblems
bool dp[n + 1][target + 1];

/ Initialize all values to false


for (int i = 0; i <= n; i++) {
for (int j = 0; j <= target; j++)
{ if (j == 0)
dp[i][j] = true; // A sum of 0 is always possible with an empty subset
else if (i == 0)
dp[i][j] = false; // No elements to form a positive sum
}
}

/ Fill the subset sum table


for (int i = 1; i <= n; i++) {
for (int j = 1; j <= target; j++) {
/ If the current element is greater than the target sum, exclude
it if (set[i - 1] > j) {
dp[i][j] = dp[i - 1]
[j]; } else {

//Check if the sum can be obtained by including or excluding the current


68
element
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - set[i - 1]];
}
}
}

/ Return the result in the bottom-right cell of the


table return dp[n][target];
}

int main() {
int n, target;

/ Input the number of elements in the set


printf("Enter the number of elements in the set:
"); scanf("%d", &n);

/ Allocate memory for the set


int *set = (int *)malloc(n * sizeof(int));
if (set == NULL) {
printf("Memory allocation failed\n");
return 1;
}

/ Input the elements of the set


printf("Enter the elements of the set:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &set[i]);
}

/ Input the target sum


printf("Enter the target sum: ");
scanf("%d", &target);

/ Check if there is a subset with the given


sum if (isSubsetSum(set, n, target)) {
printf("There is a subset with the given sum.\
n"); } else {
printf("There is no subset with the given sum.\n");
}

/ Free allocated memory


free(set);

return 0;
}

69
SAMPLE OUTPUT

RESULT

Thus the program to implement subset sum problem was executed successfully.

70
EX NO: 19 Write a program for Solving 15-Puzzle problem
DATE:

AIM
To write a program for Solving 15-Puzzle problem

ALGORITHM:

1. Initialization:

Create the priority queue and initialize it with the starting puzzle configuration.
Use the Manhattan distance heuristic to estimate the cost.
2. Node Expansion:

Continuously dequeue the node with the lowest cost from the priority queue.
Check if it matches the goal configuration.
Generate and enqueue child nodes corresponding to valid tile moves.
3. Goal Check:

If a node matches the goal configuration, print the solution path.


4. Solution Path:

Trace the path from the goal node back to the start node to show the sequence of
moves.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>

/ Size of the
puzzle #define N 4

/ Define a structure for the puzzle state


typedef struct {
int puzzle[N][N]; // 2D array to represent the puzzle
int x, y; // Coordinates of the blank tile
int cost; // Cost to reach this state
int level; // Depth of this state in the search tree
struct Node* parent; // Pointer to the parent
node } Node;

/ Define a priority queue


node typedef struct {
Node* node;
int priority;
} PQNode;

71
/ Priority queue for A*
algorithm typedef struct {
PQNode* nodes;
int size;
int capacity; }
PriorityQueue;

/ Function prototypes
int calculateManhattanDistance(int puzzle[N]
[N]); void swap(int* a, int* b);
Node* createNode(int puzzle[N][N], int x, int y, int newX, int newY, int level,
Node* parent);
PriorityQueue* createPriorityQueue(int capacity);
void enqueue(PriorityQueue* pq, Node* node, int
priority); Node* dequeue(PriorityQueue* pq);
bool isGoal(int puzzle[N][N]);
void printPuzzle(int puzzle[N][N]);
bool isValid(int x, int y);
void printSolution(Node* root);
void solvePuzzle(int start[N][N], int x, int y);

// Manhattan distance heuristic function


int calculateManhattanDistance(int puzzle[N][N])
{ int distance = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int value = puzzle[i][j];
if (value != 0) {
int targetX = (value - 1) / N;
int targetY = (value - 1) % N;
distance += abs(i - targetX) + abs(j - targetY);
}
}
}
return distance;
}

// Swap two integers


void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Create a new node


Node* createNode(int puzzle[N][N], int x, int y, int newX, int newY, int level,
Node* parent) {
Node* node = (Node*)malloc(sizeof(Node));
memcpy(node->puzzle, puzzle, sizeof(node->puzzle));
swap(&node->puzzle[x][y], &node->puzzle[newX][newY]);
node->x = newX;
node->y = newY;
node->level = level;

72
node->parent = parent;
node->cost = calculateManhattanDistance(node->puzzle) +
level; return node;
}

// Create a priority queue


PriorityQueue* createPriorityQueue(int capacity) {
PriorityQueue* pq =
(PriorityQueue*)malloc(sizeof(PriorityQueue)); pq->nodes =
(PQNode*)malloc(capacity * sizeof(PQNode)); pq->size = 0;
pq->capacity = capacity;
return pq;
}

// Enqueue a node in the priority queue


void enqueue(PriorityQueue* pq, Node* node, int priority) {
int i = pq->size++;
while (i && priority < pq->nodes[(i - 1) / 2].priority)
{ pq->nodes[i] = pq->nodes[(i - 1) / 2];
i = (i - 1) / 2;
}
pq->nodes[i].node = node;
pq->nodes[i].priority = priority;
}

/ Dequeue a node from the priority queue


Node* dequeue(PriorityQueue* pq) {
if (pq->size == 0) return NULL;
Node* min = pq->nodes[0].node;
PQNode last = pq->nodes[--pq-
>size]; int i = 0, child;
while ((child = 2 * i + 1) < pq->size) {
if (child + 1 < pq->size && pq->nodes[child].priority > pq->nodes[child
+ 1].priority)
child++;
if (last.priority <= pq->nodes[child].priority) break;
pq->nodes[i] = pq->nodes[child];
i = child;
}
pq->nodes[i] = last;
return min;
}

/ Check if the current puzzle is the goal


state bool isGoal(int puzzle[N][N]) {
int goal[N][N] =
{ {1, 2, 3, 4},
{5, 6, 7, 8}, {9,
10, 11, 12},
{13, 14, 15, 0}
};
return memcmp(puzzle, goal, sizeof(goal)) == 0;
}
73
// Print the puzzle
void printPuzzle(int puzzle[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (puzzle[i][j] == 0)
printf(" ");
else
printf("%2d ", puzzle[i][j]);
}
printf("\n");
}
}

/ Check if a move is valid


bool isValid(int x, int y) {
return x >= 0 && x < N && y >= 0 && y < N;
}

/ Print the solution path


void printSolution(Node* root) {
if (root == NULL) return;
printSolution(root->parent);
printPuzzle(root->puzzle);
printf("\n");
}

// Solve the 15-puzzle problem


void solvePuzzle(int start[N][N], int x, int y)
{ PriorityQueue* pq = createPriorityQueue(10000);
Node* root = createNode(start, x, y, x, y, 0, NULL);
enqueue(pq, root, root->cost);

while (pq->size > 0) {


Node* min = dequeue(pq);

if (isGoal(min->puzzle)) {
printf("Solution found:\n");
printSolution(min);
return;
}

int dx[] = {1, -1, 0, 0};


int dy[] = {0, 0, 1, -1};
for (int i = 0; i < 4; i++) {
int newX = min->x + dx[i];
int newY = min->y + dy[i];
if (isValid(newX, newY)) {
Node* child = createNode(min->puzzle, min->x, min->y, newX, newY,
min->level + 1, min);
enqueue(pq, child, child->cost);
}
}
}

74
printf("No solution exists.\n");
}

int main() {
int start[N][N] = {
{5, 1, 2, 3},
{9, 6, 10, 4},
{13, 7, 14, 8},
{0, 11, 15, 12}
};

int x = 3, y = 0; // Coordinates of the blank tile in the start configuration


solvePuzzle(start, x, y);

return 0;
}

75
SAMPLE OUTPUT:

Input

Output

RESULT
Thus the program for Solving 15-Puzzle problem was executed successfully.

76

You might also like