0% found this document useful (0 votes)
25 views65 pages

Staff Copy-Algorithm

Uploaded by

21cs105
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
25 views65 pages

Staff Copy-Algorithm

Uploaded by

21cs105
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 65

LABORATORY MANUAL

for

CS3401 ALGORITHMS LABORATORY


Of

B.E (COMPUTER SCIENCE AND


ENGINEERING)
(Anna University Regulation 2021)
For the Batch (2021 to 2025)

Semester: IV

ACADEMIC YEAR: 2022-2023

DEPARTMENT OF COMPUTER SCIENCE AND ENGINERRING


KCG COLLEGE OF TECHNOLOGY,
CHENNAI – 600 097
REG. No. …………………………….

LABORATORY RECORD
Course Code: ………………….

Name of the Course: ……………………………………………………………………………..

It is to certify that this is a bonafide record of the work carried out by

…………………………………………………………………………………………………………………………of..…………

……….semester………………………………………department, during the odd semester of the

academic year 2022-2023.

Faculty In-charge: …………………………………… HOD…………………………………………….

Int. Examiner: ………………………………………… Ext. Examiner ………………………………..

Date of the Examination: ……………………


VISION OF THE COLLEGE
KCG College of Technology aspires to become a globally recognized center of
excellence for science, technology &engineering education, committed to quality
teaching, learning and research while ensuring for every student a unique educational
experience which will promote leadership, job creation, social commitment and service
to nation building
MISSION OF THE COLLEGE

• Disseminate knowledge in a rigorous and intellectually stimulating environment


• Facilitate socially responsive research, innovation and entrepreneurship
• Foster holistic development and professional competency
• Nurture the virtue of service and an ethical value system in the young minds

VISION OF THE DEPARTMENT


The department of Computer Science and Engineering desires to become a
prominent center of excellence for producing competent IT professionals for
providing software and software enabled solutions.

MISSION OF THE DEPARTMENT

• Impart knowledge of fundamentals as well as emerging trends in Information Technology


• Inculcate innovative and entrepreneurial abilities as well as ethical values among the students
• Establish computing facilities and research activities to enhance the knowledge
• Enhancing competency of faculty with the advanced technologies in Information Technology
PROGRAMME EDUCATIONAL OBJECTIVES
The graduates of B.E COMPUTER SCIENCE AND ENGINEERING will

PEO 1 Have successful career as software professional (or) entrepreneur (or)


researcher in computer science and relevant disciplines.

PEO 2
Analyze, design, develop, test and deploy appropriate solutions for real
world computing problems.
PEO 3 Apply software engineering principles at process, project and product levels.
PEO4 Exhibit ethical attitude and social responsibility in their profession.

PROGRAMME OUTCOMES AND PROGRAM ME SPECIFIC OUTCOMES


After successful completion of B.E Computer Science and Engineering, the students will be
able to:

Apply the knowledge of mathematics, science, engineering fundamentals, and an


PO 1
engineering specialization to the solution of complex engineering problems.

Identify, formulate, research literature, and analyze complex engineering problems


PO 2 reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.

Design solutions for complex engineering problems and design system components or
PO 3 processes that meet the specified needs with appropriate consideration for the public health
and safety, and the cultural, societal, and environmental considerations.

Use research-based knowledge and research methods including design of experiments,


analysis and interpretation of data, and synthesis of the information to provide valid
PO 4 conclusion

Create, select, and apply appropriate techniques, resources, and modern engineering and IT
PO 5 tools including prediction and modelling to complex engineering activities with an
understanding of the limitations.
Apply reasoning informed by the contextual knowledge to assess societal, health, safety,
PO 6 legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

Understand the impact of the professional engineering solutions in social and environmental
PO 7
contexts, and demonstrate the knowledge of, and for sustainable development.

Apply ethical principles and commit to professional ethics and responsibilities


PO 8
and norms of the engineering practice.

Function effectively as an individual, andas a member or leader in diverse teams,


PO 9
and in multidisciplinary settings.

Communicate effectively on complex engineering activities with the engineering community


and with society at large, such as, being able to comprehend an write effective reports and
PO 10
design documentation, make effective presentations, and give and receive clear instructions.

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
PO 11 multidisciplinary environment

Recognize the need for, and have the preparation and ability to engage in
PO 12 independent life- long learning in the broadest context of technological change.

PROGRAMME SPECIFIC OUTCOMES (PSO)


PSO Description of PSO

Apply knowledge pertaining to software engineering principles, computer hardware and


PSO 1 architecture, principles of algorithms & programming skills to analyze complex problems
in computer science engineering and related domains.

Use compiler tool, CASE tool, graphic tool, app development tools, network
simulator, security and analysis tools, cloud and grid tool kits, database
PSO 2
management tools, web development frameworks for providing appropriatesolutions.

PSO 3 Demonstrate professional & ethical behavior while providing IT based solutions.
Course Outcomes:
Upon completion of this course, the student will be able to:

Cognitive
Sl.No Course Outcomes
Level
Analyze the efficiency of algorithms using various frameworks
CO 1 K4
Apply graph algorithms to solve problems and analyze their
CO 2 efficiency. K3

Make use of algorithm design techniques like divide and conquer, dynamic
programming and greedy techniques to solve problems K4
CO 3
Use the state space tree method for solving problems.
CO 4 K4
Solve problems using approximation algorithms and randomized algorithms
CO 5 K6
DEPARTMENT OF COMPUTER SCIENCE AND ENGINERRING

CS3401 ALGORITHM LABORATORY


Index
Exp Name of the Experiment Page Date Signature
No. No

1
Implement Linear Search and Binary
Search
2 Pattern Searching

3 Insertion Sort and Heap sort


4
Develop a program to implement graph
traversal using Breadth First Search.
5
Develop a program to implement graph
traversal using Depth First Search

6 shortest paths to other vertices using


Dijkstra’s algorithm.

7 Prim’s algorithm.

8 Floyd’s algorithm

9 Compute the transitive closure of a given


directed graph using Warshall's algorithm.
Implement Merge sort and Quick sort methods
10 to sort an array of elements

11 . Implement N Queens problem using


Backtracking.

Traveling Salesperson problem


12

finding the kth smallest number


13
ANNA UNIVERSITY
CS3401 ALGORITHMS LABORATORY
REGULATION 2021

LIST OF EXPERIMENTS LTPC


004 2
1. Implement Linear Search. Determine the time required to search for an element.

2. Implement recursive Binary Search. Determine the time required to search an element.

3. 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 [ ]. You may assume that n > m.

4. Sort a given set of elements using the Insertion sort and Heap sort methods and determine
the time required to sort the elements.

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. Using Dijkstra's algorithm, develop a program to find the shortest paths to other vertices
from a given vertex in a weighted connected graph.

8. Find the minimum cost-spanning tree of a given undirected graph using Prim’s algorithm.
Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.
9. Compute the transitive closure of a given directed graph using Warshall's algorithm.

10. Develop a program to find out the maximum and minimum numbers in a given list of
numbers using the divide and conquer technique.

11. Implement Merge sort of an array of elements and determine the time required to sort.

12. Implement the N Queens problem using Backtracking.

13. Implement any scheme to find the optimal solution for the Traveling Salesperson problem.

14. Implement randomized algorithms for finding the kth smallest number.

TOTAL:30

7
EX .NO.1
Date: Implement Linear Search and Binary Search

AIM:

To implement Linear search and Binary search and determine the time required to
search for an element

ALGORITHM:
Binary Search

Step 1: if (low > high) then return -1


Step 2: if (low < high) the mid=(low + high)/2
Step 3: X be a key. If a[mid] = X then return mid
Step 4: If a[mid] > X then search for X from a[low] to a[mid-1]
Step 5: If a[mid] < X then search for X from a[mid + 1] to a[high]
Linear Search

Set i to 0.
If Li = T, the search terminates successfully; return i.
Increase i by 1.
If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.

PROGRAM

#include<stdio.h>
#include<conio.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;
8
int n,i,a
[max],k,op,low,high,pos;
clock_tbegin,end;
clrscr();
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;
begin=clock();
pos=binsearch(n,a,k,low,high)
;end=clock();
if(pos==-1)
printf("\n\nUnsuccessful
search");

else
printf("\n element %d is found at position %d",k,pos+1);
printf("\n Time Taken is %lf CPU1 cycles \n",(end-begin)/CLK_TCK);
getch();
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);
begin=clock();
pos=linsearch(n,a,k)
;end=clock();
if(pos==-1)

9
printf("\n\n Unsuccessful
search");else
printf("element %d is found at position %d",k,pos+1);
printf("\n Time taken is %lf CPU cycles \n",(end-begin)/CLK_TCK);
getch();
break;
default:printf("Invalid choice entered
\n");exit(0);
}
printf("\n Do you wish to run again(1/0)
\n");scanf("%d",&ch);
}
getch();
}
intbinsearch(intn,int a[],intk,intlow,int high)
{
int mid;
delay(1000);
mid=(low+high)/2
;if(low>high)
return -1;
if(k==a[mid])
return(mid);
else

if(k<a[mid])
returnbinsearch(n,a,k,low,mid-1);
else
returnbinsearch(n,a,k,mid+1,high);
}
intlinsearch(intn,int a[],int k)
{
delay(1000)
;if(n<0)
return -1;
if(k==a[n-
1])
return (n-
1);else
returnlinsearch(n-1,a,k);
}

10
OUTPUT

Result
Thus the C program for Linear search and binary search has executed successfully

11
REVIEW QUESTIONS:

1. What is binary search?

2. Define dynamic programming.

3.Define linear Search.

4.Define Graph.

12
Ex No: 2
PATTERN SEARCHING
Date:

AIM:
To write a C program for a given text and pattern and write a search function that prints all occurrences
of pattern in text.

ALGORITHM:

Algorithm-NAVE_STRING_MATCHING (T, P)
for i←0 to n-m do
if P[1......m] == T[i+1.....i+m] then
print "Match Found"
end
end

PROGRAM:

// C program for Naive Pattern Searching algorithm


#include <stdio.h>
#include <string.h>

void search(char* pat, char* txt)


{
int M = strlen(pat);
int N = strlen(txt);
/* A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++) {
int j;
/* For current index i, check for pattern match */
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j== M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
printf("Pattern found at index %d \n", i);
}
}
// Driver's code
int main()
{
char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
// Function call
search(pat, txt);
return 0;
}

13
OUTPUT:

RESULT:
Thus the program was executed successfully and output was verified

14
REVIEW QUESTIONS:
1. What are algorithm design techniques?

2. What are the characteristics of an algorithm?

3. How will you measure input size of algorithms?

4. Define multistage graph

15
Ex. No:3
HEAP SORT
Date:

AIM:

To Implement Heap sort methods and determine the time required to sort the elements ..

ALGORITHM:

The Heap sort algorithm to arrange a list of elements in ascending order is performed using following steps...

Step 1 - Construct a Binary Tree with given list of Elements.

Step 2 - Transform the Binary Tree into Min Heap.

Step 3 - Delete the root element from Min Heap using Heapify method.

Step 4 - Put the deleted element into the Sorted list.

Step 5 - Repeat the same until Min Heap becomes empty.

Step 6 - Display the sorted lis

PROGRAM:

#include<stdio.h> #include<conio.h>
#include<time.h>
void heapsort(intn,intarr[]);
voidheapy(intn,intarr[]); void
adjust(intn,intarr[]); void heapsort(intn,intarr[])
{
inti,item; delay(100); heapy(n,arr);
for(i=n;i>=1;i--)
{
item=arr[1];arr[1]=arr[i];
arr[i]=item; adjust(i,arr);
}
16
}
voidheapy(intn,intarr[])
{
inti,j,k,item; for(i=1;i<=n;i++)
{
item=arr[i];j=i;
k=j/2;
while(k!=0 && item>arr[k])
{
arr[j]=arr[k];j=k;
k=j/2;
}
arr[j]=item;
}
}
void adjust(intn,intarr[])
{
inti,j,item;j=1;
item=arr[j];i=j*2; while(i<n)
{
if((i+1)<n)
{
if(arr[i]<arr[i+1])i++;
}
if(item<arr[i])
{
arr[j]=arr[i];j=i;
i=2*j;
}
else break;
}
arr[j]=item;

}
void main()
{
inti,n,arr[20]; clock_tend,start;
clrscr();
printf("\nEnter the number of Elements: \t");scanf("%d",&n);
printf("\nEnter the %d Elements:",n);for(i=1;i<=n;i++)
scanf("%d",&arr[i]);start=clock();
heapsort(n,arr); end=clock();
printf("\nSorted Elements are\n");for(i=1;i<=n;i++)
17
printf("%d ",arr[i]);
printf("\nTime taken by Heapsort %f CPU Cycle",(end-start)/CLK_TCK);getch();
}

Output

RESULT:

Thus The program for Heap Sort Executed Successfully and Output was verified.

18
REVIEW QUESTIONS

1.What is the typical running time of a heap sort algorithm?

2.What is a Heap?

3.What is a Binary heap,and how do you implement it?

4. What are the two phases of heap sort?

19
Ex. No:4
BREADTH FIRST SEARCH
Date:

AIM:

Aim:- Program to implement graph traversal using Breadth First Search.

PROGRAM

#include<stdio.h> #include<conio.h>
void distance(int,int);int a[10][10];
void main()
{
inti,j,n;
clrscr();
printf("\n enter the number of vertices in the diagraph:"); scanf("%d",&n);
printf("\n enter the adjacency matrix\n"); for(i=1;i<=n;i++)
20
for(j=1;j<=n;j++) scanf("%d",&a[i][j]);
for(i=1;i<=n;i++)
{
printf("\n the starting vertex is %d\n",i); distance(i,n);
printf("\n\t press enter for other source vertex\n");
getch();
}
}
void distance(intv,int n)
{
int queue[40],visited[20],dis[20],front,rear,i,j; for(i=1;i<=n;i++)
visited[i]=dis[i]=0; front=rear=0;
queue[rear++]=v; visited[v]=1;
do
{
i=queue[front++]; for(j=1;j<=n;j++)
if(a[i][j]&&!visited[j])
{
dis[j]=dis[i]+1; queue[rear++]=j;
visited[j]=1;
printf("\n\t the vertex %d to %d is of distance=%d\n",v,j,dis[j]);
}
}
while(front<rear);
}

21
OUTPUT

RESULT:

Thus the C program for graph traversal using breadth first search has executed successfully

22
REVIEW QUESTIONS:

1.What is the runtime of BFS?

2.Is BFS a stack or queue?

3.Difference between BFS and DFS

4. Is breadth first search a backtracking algorithm?

23
Ex. No:5 DEPTH FIRST SEARCH
Date:

AIM:
Program to implement graph traversal using Depth First Search.

Algorithm

PROGRAM

#include<stdio.h>
#include<conio.h>
voiddfs(intn,int cost[10][10],intu,int s[])
{
int v; s[u]=1;
for(v=0;v<n;v++)
{
if(cost[u][v]==1 && s[v]==0)
{
dfs(n,cost,v,s);
}
}
}
void main()
{
Int n,i,j,cost[10][10],s[10],connected,flag;
clrscr();
printf("\n enter the number of nodes\n");
scanf("%d",&n);

24
printf("\n enter the adjacency matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cost[i][j]);
]
}
connected=0; for(j=0;j<n;j++)
{
for(i=0;i<n;i++) s[i]=0;
dfs(n,cost,j,s); flag=0;
for(i=0;i<n;i++)
{
if(s[i]==0) flag=1;
}
if(flag==0) connected=1;
}

if(connected==1)
printf("graph is connected\n");
else
printf("graph is not connected\n");
getch();
}

25
RESULT
Thus the C program for graph traversal using depth first search has executed successfully

26
REVIEW QUESTIONS

1.Difference between Compile and Running Time.

2. What are three parts of algorithm?

3.Define linear programming

4. What is a state space tree?

27
Ex. No: 6
Date: DIJKSTRA’S ALGORITHM

AIM
To form a given vertex in a weighted connected graph and to find shortest paths to other vertices using Dijkstra’s
algorithm.

ALGORITHM
Create a shortest path tree set that keeps track of vertices included in shortest path tree,
i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty.
- Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE.
- Assign distance value as 0 for the source vertex so that it is picked first.
- While shortest path tree set doesn’t include all vertices
a) Pick a vertex u which is not there in shortest path tree set and has minimum distance value.
b) Include u to shortest path tree set
c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent
vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than
the distance value of v, then update the distance value of v.

PROGRAM

#include<stdio.h>
main ()
{
int n, cost[15][15], i, j, s[15], v,dist[15],num,min;
printf ("Enter the vertices please\n");
scanf ("%d",&n);
printf ("Enter the cost of the edges please\n");
printf ("Enter 999 if the edge is not present or for the self loop\n");
for (i = 1; i<= n; i++)
for (j = 1; j<= n; j++)
scanf ("%d", &cost[i][j]);
printf ("Enter the Source vertex please\n");
scanf ("%d", &v);
for (i = 1; i<= n; i++)
{
s[i] = 0;
dist[i] = cost[v][i];
}
s[v] = 1;
dist[v] = 0;
for (num = 2; num <= n - 1; num++)
{
min = 999;
28
for (i = 1; i<= n; i++)
if (s[i] == 0 &&dist[i]<min)
{
min = dist[i];
j = i;
}
s[j]= 1;
for (i = 1; i<= n; i++)
{
if (s[i] == 0)
{
if (dist[i] >(dist[j] + cost[j][i]))
dist[i] = (dist[j] + cost[j][i]);

}
}
}
printf ("VERTEX\tDESTINATION\tCOST\n");
for (i = 1; i<= n; i++)
printf ("%d\t %d\t\t %d\n", v, i, dist[i]);
}

29
OUTPUT
Enter the vertices please
4
Enter the cost of the edges please
Enter 999 if the edge is not present or for the self loop
999 3 4 7
3 999 999 2
4 999 999 4
7 2 4 999
Enter the Source vertex please
1
VERTEX DESTINATION COST
1 1 0
1 2 3
1 3 4
1 4 5

RESULT
The program was verified and executed successfully.

30
REVIEW QUESTIONS

1. What is the time complexity of Dijikstra’s algorithm?

2.Can you give me some examples where you would use Dijkstra’s algorithm?.

3. What’s the difference between Breadth First Search and Depth First Search?

4. Is it possible to use Dijkstra’s algorithm for directed graphs?

31
Ex. No:7
PRIMS'S ALGORITHM
Date:

AIM:
To find the minimum spanning tree of given undirected graph using prims's algorithm.
ALGORITHM
Step 1: start the program
Step 2: Initialize the algorithm by choosing the
source vertex.
Step 3:Find the minimum weight edge connected to
the source node and another node and add
it to the tree.
Step 4:Keep repeating this process until we find minimum spanning tree. To write a shell program to
find the sum of n numbers.

PROGRAM

#include<stdio.h>

int main()

int cost[20][20],t[20][20],near1[20],a[20];

int i,j,n,min,minimum,k,l,mincost,c,b;

printf("\n enter the number of nodes");

scanf("%d",&n);

printf("\n enter the adjacency matrix\n");

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

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

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

minimum=cost[1][1];

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

32
for(j=1;j<=n;j++)

if(minimum>=cost[i][j])

minimum=cost[i][j];

k=i;

l=j;

mincost=minimum;

t[1][1]=k;

t[1][2]=l;

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

if(cost[i][l]<cost[i][k])

near1[i]=l;

else

near1[i]=k;

near1[k]=near1[l]=0;

for(i=2;i<=n-1;i++)

min=999;

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

{
33
if(near1[j]!=0)

a[j]=cost[j][near1[j]];

min=a[j];

c=near1[j];

b=j;

printf("\n");

mincost=mincost+cost[b][c];

near1[b]=0;

for(k=1;k<=n;k++)

if((near1[k]!=0) &&(cost[k][near1[k]]>cost[k][b]))

near1[k]=b;

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

34
OUTPUT

enter the number of nodes 4

enter the adjacency matrix

1526

1478

3567

3245

the cost of minimum spanning tree is=6

--------------------------------

Process exited after 28.35 seconds with return value 0

Press any key to continue . . .

RESULT

Thus the program was executed successfully and output was verified.

35
REVIEW QUESTIONS

1.What are the conditions for Prim's algorithm?

2.What is linear data structure?

3.What are graphs and their uses?

4.How does Prim's algorithm find a spanning tree?

36
Ex. No:8 FLOYDS ALGORITHM

Date:

AIM:

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


ALGORITHM:

For a graph with N vertices:

Step 1: Initialize the shortest paths between any 2 vertices with Infinity.

Step 2: Find all pair shortest paths that use 0 intermediate vertices, then find the
shortest paths that use 1 intermediate vertex and so on.. until using all N vertices as
intermediate nodes.

Step 3: Minimize the shortest paths between any 2 pairs in the previous operation.

Step 4: For any 2 vertices (i,j) , one should actually minimize the distances between
this pair using the first K nodes, so the shortest path will be:
min(dist[i][k]+dist[k][j],dist[i][j]).

dist[i][k] represents the shortest path that only uses the first K vertices, dist[k][j]
represents the shortest path between the pair k,j. As the shortest path will be a
concatenation of the shortest path from i to k, then from k to j.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],a[10][10];
voidall_paths(int[10][10],int[10][10],int);
int min1(int,int);
void main()
{
inti,j,n;
clrscr();
printf("\n enter the number of vertices\n");
scanf("%d",&n);
37
printf("enter the adjacency matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
all_paths(cost,a,n);
printf("\n shortest path obtained is\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("\t%d",a[i][j]);
printf("\n");
}
getch();
}

voidall_paths(int cost[10][10],int a[10][10],int n)


{
inti,j,k; for(i=1;i<=n;i++)
for(j=1;j<=n;j++) a[i][j]=cost[i][j];
for(k=1;k<=n;k++)for(i=1;i<=n;i++)
for(j=1;j<=n;j++)

a[i][j]=min1(a[i][j],

a[i][k]+a[k][j]);

int min1(inta,int b)

return(a<b)?a:b;

38
OUTPUT

RESULT
Thus the program was executed successfully and output was verified.

39
REVIEW QUESTIONS:

1. What approaches are being followed in Floyd’s Warshalls algorithm?

2.What algorithms are used to find the shortest path from a source node to all other nodes
in a
weighted graph?

2. What should be considered when designing an algorithm?

4, What is the best time complexity we can achieve to precompute all-pairs shortest paths
in a weighted graph?

40
Ex. No:9 TRANSITIVE CLOSURE OF A GIVEN DIRECTED GRAPH USING
WARSHALL'S ALGORITHM
Date:

AIM:

To compute the transitive closure of a given directed graph using Warshall’s algorithm.

ALGORITHM:
path exists between two vertices i, j,
• there is an edge from i to j; or
• there is a path from i to j going through vertex 1; or
• there is a path from i to j going through vertex 1 and/or 2; or
• there is a path from i to j going through vertex 1, 2, and/or 3; or
• there is a path from i to j going through any of the other vertices 3 3 3
Recurrence relating elements R(k) to elements of
R(k-1) is: R(k) [i,j] = R(k-1)[i,j] or (R(k-1)[i,k] and R(k-1)[k,j])
It implies the following rules for generating R(k) from R(k-1):

Rule 1 If an element in row i and column j is 1 in R(k-1) , it remains 1 in R(k)

Rule 2 If an element in row i and column j is 0 in R(k-1) , it has to be changed to 1 in R(k)


it has to be changed to 1 in R if and only if (k) if and only if the element in its row i and
column k and the element in its column j and row k are both 1’s in R(k-1)

PROGRAM:

#include<stdio.h>
#include<conio.h>int a[10][10];
void main()
{
intj,k,n;
clrscr();
printf("enter the number of vertice\n");scanf("%d",&n);
printf("enter the adjacency matrix");for(i=1;i<=n;i++)
for(j=1;j<=n;j++)

scanf("%d",&a[i][j]);for(k=1;k<=n;k++)
for(i=1;i<=n;i++) for(j=1;j<=n;j++)
a[i][j]=a[i][j] || a[i][k] && a[k][j]; printf("\n the transitive

41
closure is\n");for(i=1;i<=n;i++)
{

}
}
getch();

OUTPUT:

RESULT:
Thus the program is computed, executed successfully and the output is verified.

42
REVIEW QUESTIONS:
1. What are asymptotic notations?

2. What are some examples of divide and conquer algorithms?

3. How many spanning trees can a graph has?

4. What is the principal strength of brute force approach?

14
Ex. No:10 QUICK SORT

Date:

Aim
To sort an array of N numbers using Quick sort.

Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Select an pivot element x from Ai
5. Divide the array into 3 sequences: elements < x, x, elements > x
6. Recursively quick sort both sets (Ai < x and Ai > x)
7. Stop

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<time.h>
void quicksort(int[],int,int);int
partition(int[],int,int); void main()
{
inti,n,a[20],ch=1;clock_tstart,end;
clrscr(); while(ch)
{
printf("enter the number of elements\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++) scanf("%d",&a[i]);
start=clock();
quicksort(a,0,n-1);end=clock();
printf("the sorted array elements are \n");
for(i=0;i<n;i++)
printf("\n%d",a[i]);
printf("timetaken =%lf",(end-start)/CLK_TCK);
printf("\n do u want to continue (0/1) \n");

15
scanf("%d",&ch);
}
getch();
}
void quicksort(int a[],intlow,int high)
{
int mid; if(low<high)
{
mid=partition(a,low,high);
quicksort(a,low,mid-1);
quicksort(a,mid+1,high);
}
}
int partition(int a[],intlow,int high)
{
intkey,i,j,temp,k;delay(500);
key=a[low]; i=low+1;
j=high; while(i<=j)
{
while(i<=high && key>=a[i])i=i+1;
while(key<a[j])j=j-1;
if(i<j)
{
temp=a[i]; a[i]=a[j]; a[j]=temp;
}
else
{
k=a[j]; a[j]=a[low];a[low]=k;
}
}
return j;
}

16
OUTPUT:

RESULT

Thus an array was sorted using quick sort's divide and conquer method.

17
REVIEW QUESTIONS

1. What are the types of sorting available in C?

2. Mention the various types of searching techniques in C.

3.Define Quick sort.

4. Define Rehashing?

18
Ex. No:11 IMPLEMENTATION OF N QUEENS PROBLEM USING BACKTRACKING

Date:

AIM
To solve N Queens problem using backtracking

ALGORITHM
Step 1 - Place the queen row-wise, starting from the left-most cell.

Step 2 - If all queens are placed then return true and print the solution matrix.

Step 3 - Else try all columns in the current row.

Condition 1 - Check if the queen can be placed safely in this column then mark the current cell
[Row, Column] in the solution matrix as 1 and try to check the rest of the problem recursively by
placing the queen here leads to a solution or not.

Condition 2 - If placing the queen [Row, Column] can lead to the solution return true and print
the solution for each queen's position.

Condition 3 - If placing the queen cannot lead to the solution then unmark this [row, column]
in the solution matrix as 0, BACKTRACK, and go back to condition 1 to try other rows.

Step 4 - If all the rows have been tried and nothing worked, return false to trigger backtracking.

PROGRAM

#include<stdio.h>

#include<math.h>

int board[20],count;

int main()

{
19
int n,i,j;

void queen(int row,int n);

printf(" - N Queens Problem Using Backtracking -");

printf("\n\nEnter number of Queens:");

scanf("%d",&n);

queen(1,n);

return 0;

//function for printing the solution

void print(int n)

int i,j;

printf("\n\nSolution %d:\n\n",++count);

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

printf("\t%d",i);

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

printf("\n\n%d",i);

for(j=1;j<=n;++j) //for nxn board

if(board[i]==j)

printf("\tQ"); //queen at i,j position

else

20
printf("\t-"); //empty slot

/*funtion to check conflicts

If no conflict for desired postion returns 1 otherwise returns 0*/

int place(int row,int column)

int i;

for(i=1;i<=row-1;++i)

//checking column and digonal conflicts

if(board[i]==column)

return 0;

else

if(abs(board[i]-column)==abs(i-row))

return 0;

return 1; //no conflicts

//function to check for proper positioning of queen

void queen(int row,int n)

21
int column;

for(column=1;column<=n;++column)

if(place(row,column))

board[row]=column; //no conflicts so place queen

if(row==n) //dead end

print(n); //printing the board configuration

else //try queen with next position

queen(row+1,n);

22
OUTPUT:
Enter number of Queens:4

Solution 1:

1 2 3 4

1 - Q - -

2 - - - Q

3 Q - - -

4 - - Q -

Solution 2:

1 2 3 4

1 - - Q -

2 Q - - -

3 - - - Q

4 - Q - -

23
RESULT
Thus the c program to solve N Queens problem using backtracking implemented successfully.

24
Review Questions
1.Define Backtracking

2.Define Greedy Method.

3.What is the difference between Branch and bound and greedy method?

4.Define Dynamic programming.

25
Ex. No:-12 TRAVELLING SALESMAN PROBLEM
Date:

AIM:
To Implement any scheme 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:
Step1: start the program.

Step2: First of all, we have to create two primary data holders.

o First of them is a list that can hold the indices of the cities in terms of the input
matrix of distances between cities
o And the Second one is the array which is our result

Step3: Perform traversal on the given adjacency matrix tsp[][] for all the city and if the cost of
reaching any city from the current city is less than the current cost the update the cost.

Step4: Generate the minimum path cycle using the above step and return their minimum cost.

Step5: stop the program.

PROGRAM

#include <stdio.h>
int matrix[25][25], visited_cities[10], limit, cost = 0;

int tsp(int c)
{
int count, nearest_city = 999;
int minimum = 999, temp;
for(count = 0; count < limit; count++)
{
if((matrix[c][count] != 0) && (visited_cities[count] == 0))
{
if(matrix[c][count] < minimum)
{
minimum = matrix[count][0] + matrix[c][count];
26
}
temp = matrix[c][count];
nearest_city = count;
}
}
if(minimum != 999)
{
cost = cost + temp;
}
return nearest_city;
}

void minimum_cost(int city)


{
int nearest_city;
visited_cities[city] = 1;
printf("%d ", city + 1);
nearest_city = tsp(city);
if(nearest_city == 999)
{
nearest_city = 0;
printf("%d", nearest_city + 1);
cost = cost + matrix[city][nearest_city];
return;
}
minimum_cost(nearest_city);
}

int main()
{
int i, j;
printf("Enter Total Number of Cities:\t");
scanf("%d", &limit);
printf("\nEnter Cost Matrix\n");
for(i = 0; i < limit; i++)
{
printf("\nEnter %d Elements in Row[%d]\n", limit, i + 1);
for(j = 0; j < limit; j++)
{
scanf("%d", &matrix[i][j]);
}

27
visited_cities[i] = 0;
}
printf("\nEntered Cost Matrix\n");
for(i = 0; i < limit; i++)
{
printf("\n");
for(j = 0; j < limit; j++)
{
printf("%d ", matrix[i][j]);
}
}
printf("\n\nPath:\t");
minimum_cost(0);
printf("\n\nMinimum Cost: \t");
printf("%d\n", cost);
return 0;
}

28
OUTPUT

Enter Total Number of Cities: 4


Enter Cost Matrix

Enter 4 Elements in Row[1]


1234
Enter 4 Elements in Row[2]
5678
Enter 4 Elements in Row[3]
3456
Enter 4 Elements in Row[4]
6789
Entered Cost Matrix

1234
5678
3456
6789

Path: 1 4 3 2 1

Minimum Cost: 21

RESULT:

Thus the travelling salesman problem has been implemented and the output is executed
successfully.

29
REVIEW QUESTIONS

1. Which method is used in the traveling salesman problem?

2,Which data structure is used in travelling salesman problem?

3.What is the time complexity of TSP problem?

4. Can travelling salesman problem be solved using greedy method?

30
Ex. No:13 FINDING THE KTH SMALLEST NUMBER
Date:

AIM:

To implement randomized algorithms for finding the kth smallest number .

ALGORITHM:

1. Take the input of the data set.


2. Take the input of the value of k.
3. Call Partition().
4. Inside Partition(), rearrange the array according to the pivot using CreatePartition()
5. Get the new index of the pivot as ‘pindex’ and compare it with (k-1).
6. If both the values are equal then return the value as a result to the main().
7. If pindex > k-1, recursively call Partition() for the part before the pivot value.
8. If pindex < k-1, recursively call Partition() for the part after the pivot value.

9. Inside main(), print the kth smallest element.

10. Exit

PROGRAM:

#include<iostream>

using namespace std;

// Swapping two values.

void swap(int *a, int *b)

int temp;

temp = *a;

*a = *b;

*b = temp;

31
// Partitioning the array on the basis of values at high as pivot value.

int CreatePartition(int a[], int low, int high)

int pivot, index, i;

index = low;

pivot = high;

// Getting index of pivot.

for(i=low; i < high; i++)

if(a[i] < a[pivot])

swap(&a[i], &a[index]);

index++;

// Swapping value at high and at the index obtained.

swap(&a[pivot], &a[index]);

return index;

// Implementing Partition.

int Partition(int a[], int low, int high, int k)

int pindex;

if(low < high)

{
32
// Partitioning array using last element as a pivot.

// Recursively implementing partitioning in the direction to place the pivot at (k-1)th pivot.

pindex = CreatePartition(a, low, high);

if(pindex == k-1)

return k-1;

else if(pindex > k-1)

Partition(a, low, pindex-1, k);

else

Partition(a, pindex+1, high, k);

int main()

int n, i, k, kk;

cout<<"\nEnter the number of data element: ";

cin>>n;

int arr[n];

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

cout<<"Enter element "<<i+1<<": ";

cin>>arr[i];

cout<<"\nEnter the k for the kth smallest element: ";

cin>>k;

33
kk = Partition(arr, 0, n-1, k);

// Printing the result.

cout<<"\nThe kth smallest element: "<<arr[kk];

return 0;

OUTPUT

Enter the number of data element: 10


Enter element 1: 9
Enter element 2: 4
Enter element 3: 0
Enter element 4: 3
Enter element 5: 7
Enter element 6: 8
Enter element 7: 1
Enter element 8: 5
Enter element 9: 6
Enter element 10: 2

Enter the k for the kth smallest element: 4

The kth smallest element: 3

RESULT:

Therefore the above experiment is executed successfully.

34
REVIEW QUESTIONS:
1.Which problem is solved by greedy method?

2.How to find kth smallest element in array in C?

3. What is KTH largest and smallest element?

4. How to find Kth Smallest Element in a Binary Search Tree?

35

You might also like