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

CS3401- Algorithm lab Manual

Uploaded by

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

CS3401- Algorithm lab Manual

Uploaded by

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

SHREE VENKATESHWARA

HI-TECH ENGINEERING COLLEGE, GOBI-638 455

NAME OF THE LAB _________________________________________________________________________

University Register No:__________________________________________________________________________

Name:___________________________________________________ Roll No:______________________________

Branch:-___________________________________________________________ Batch :____________________

Certified that this is bonafide record of work done by the above student during the year
20 -20

LAB IN-CHARGE HEAD OF THE DEPARTMENT

Submitted for the practical Examination held on __________________________________________

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

S.NO DATE NAME OF THE EXPERIMENTS PAGE MARKS STAFF


NO SIGN

SEARCHING AND SORTING ALGORITHMS

1. IMPLEMENTATION OF LINEAR SEARCH

2. IMPLEMENTATION OF RECURSIVE BINARY SEARCH

3. IMPLEMENTATION OF PATTERN SEARCH

IMPLEMENTATION OF INSERTION SORT AND HEAP


4.
SORT METHODS

GRAPH ALGORITHMS

IMPLEMENTATION OF GRAPH TRAVERSAL USING


5
BREADTH FIRST SEARCH
IMPLEMENTATION OF GRAPH TRAVERSAL USING
6. DEPTH FIRST SEARCH

THE SHORTEST PATHS TO OTHER VERTICES USING


7.
DIJKSTRA’S ALGORITHM

8. UNDIRECTED GRAPH USING PRIM’S ALGORITHM

IMPLEMENTATION OF IMPLEMENT FLOYD’S


9. ALGORITHM

DIRECTED GRAPH USING WARSHALL'S ALGORITHM


10.
ALGORITHM DESIGN TECHNIQUES

IMPLEMENTATION OF THE DIVIDE AND CONQUER


11.
TECHNIQUE

IMPLEMENTATION OF MERGE SORT AND QUICK


12.
SORT METHODS

STATE SPACE SEARCH ALGORITHMS

IMPLEMENTATION OF N QUEENS PROBLEM USING


13.
BACKTRACKING

APPROXIMATION ALGORITHMS RANDOMIZED ALGORITHMS

IMPLEMENTATION OF TRAVELING SALESPERSON


14. PROBLEM

IMPLEMENTATION OF RANDOMIZED ALGORITHMS


15. FOR FINDING THE Kth SMALLEST NUMBER
Ex.No : 1
IMPLEMENTATION OF LINEAR SEARCH
Date :

AIM
To write a C++ program to perform implementation of Linear Search.

ALGORITHM
Step 1: Set i to 1
Step 2: If i > n then go to step 7
Step 3: If A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
PROGRAM
#include<iostream>
using namespace std;
class Search
{
private:
int a[10],n,key;
public:
void get_data();
void Seq_Search(int)
};
void Search::Seq_Search(int key)
{ int flag=0,mark;
for(int i=0;i<n;i++)
{//searching element from beginning of array
if (a[i]==key)
{ flag=1;//setting the flag if element found
mark=i;//marking the location of key element

1
break;
}}
if(flag==1)//flag=1 means element is found
cout<<”\n The element is present at location:”<<mark+1;
else
count<<”\n The element is not present in the array”;
} void Search::get_data()
{
cout<<”\n How Many Elements are there in an array?”;
cin>>n;
cout<<”\n Enter the elements”;
for (int i=0;i<n;i++)
cin>>a[i];
}
void main()
{
int k;
Search obj;
obj.get_data();
cout<<”\n\t Enter the element which is to be searched”;
cin>>k;
obj.Seq_Search(k);
}

OUTPUT

How MANY Elements are there in an array? 7


Enter the elements 10 20 30 40 50 60 70
Enter the element which is to be searched 50
The elements is present at location:5

RESULT
Thus the implementation of Linear search program was successfully executed.

2
Ex.No :2
IMPLEMENTATION OF RECURSIVE BINARY SEARCH
Date :

AIM
To write a C++ program to perform implementation of Recursive Binary Search.
ALGORITHM

STEP 1 : Find the midpoint of the array; this will be the element at arr[size/2]. The
midpoint divides the array into two smaller arrays: the lower half of the array consisting
of elements 0 to midpoint - 1, and the upper half of the array consisting of elements
midpoint to size - 1.

STEP 2 : Compare key to arr[midpoint] by calling the user function cmp_proc.

STEP 3: If the key is a match, return arr[midpoint]; otherwise

STEP 4: If the array consists of only one element return NULL, indicating that there is
no match; otherwise

STEP 5 :If the key is less than the value extracted from arr[midpoint] search the lower
half of the array by recursively calling search; otherwise

STEP 6 : Search the upper half of the array by recursively calling search.

PROGRAM

#include<iostream>

#define size 10

Using namespace std;

Class BINSEARCH

Private:

Int a[size];

Public:

Int low,high;

BINSEARCH();

Int get_value();

3
Int binsearch(int x,int low,int high);

};

BINSEARCH::BINSEARCH()

Low=0;

Int BINSEARCH::get_value()

Int n;

Cout<<”\n enter the total number of elements”;

Cin>>n;

Cout<<”\n enter the list of elements”;

For(int i=0;i<n;i++)

Cin>>a[i];

ruturn n;

Int BINSEARCH::binsearch(int x,int low,int high)

Int mid;

If(low>high)

Return-1;

Mid=(low+high)/2;

If(x==a[mid])

Return(mid);

Else if(x<a[mid])

Binsearch(x,low,mid-1);

Else

N=binsearch(x,mid+1,high);

4
}

Void main(void)

Int key,ans,n;

BINSEARCH obj;

Cout<<”\n\t\t\t binary search method”;

n=obj.get_value();

cout<<”\n enter the element which you want to seach”;

cin>>key;

obj.high=n-1;

ans=obj.binsearch(key,obj.low,obj.high);

if(ans!=-1)

cout<<”\n the number”<<key<<”is present in the list at location”<<ans+1;

else

cout<<”\n the number is not present in the list”;

OUTPUT

Binary search method

Enter the total number of elements 5

Enter the list of elements

10

20

30

40

50

Enter the element which you want to search 40

The number 40 is present in the list at location 4

5
RESULT
Thus the program for implementation of Binary search program was executed
successfully.

6
Ex.No : 3
IMPLEMENTATION OF PATTERN SEARCH
Date :

AIM
To write a C program to perform implementation of Pattern Search.
ALGORITHM

STEP 1 : Start the program


STEP 2 : To Enqueue an element into the circular queue, Check whether queue is Full –
Check ((rear == SIZE-1 && front == 0) || (rear== front-1)).
STEP 3: If it is full then display Queue is full. If queue is not full then, check if (rear ==
SIZE – 1 && front != 0) if it is true then set rear=0 and insert element.
STEP 4: To Dequeue an element from the circular queue, Check whether queue is Empty
means check (front==-1).
STEP 5: If it is empty then display Queue is empty. If queue is not empty then step 3
STEP 6 : Check if (front==rear) if it is true then set front=rear= -1 else check if
(front==size-1), if it is true then set front=0 and return the element

PROGRAM

#include<stdio.h>

#include<conio.h>

#include<string.h>

int n,m;

void main()

Char Txt[50],Pat[50];

int i,j;

int Search(char Txt[20],char Pat[20]);

printf(“\n Enter the Text:”);

gets(Txt);

printf(“\n Enterthe Pattern:”);

gets(Pat);

7
n=strien(Txt);

m=strien(Pat);

printf(“The matched pattern is from location %d in Text”,Search(Txt,Pat));

int Search(char T[50],char P[50])

int i,j;

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

j=0;

while(j<m)&&(P[j]==T[i+j]))

j=j+1;

If(j==m)

return i;

return-1;

OUTPUT

Enter the Text:raman likes mango

Enter the pattern:mango

The matched pattern is from location 12 in Text

RESULT

Thus the program for implementation of pattern search was executed successfully.

8
Ex.No : 04 IMPLEMENTATION OF INSERTION SORT AND HEAP SORT

Date : METHODS

AIM
To write a C++ program to implement Insertion and Heap Sort.

ALGORITHM
STEP 1 : Start the program.
STEP 2 : Create a list with the menus 1) Insertion 2) Deletion 3) Display and 4) Quit in the
list. Read the option from the user. Also define the structure nodes and member functions.
STEP 3: For insertion find the right position in the list and insert the element.
STEP 4 : Make necessary pointer changes after insertion.
STEP 5 : For deletion find the item in the list and delete the element. If the list is empty, print
an error message as “List is Empty”.
STEP 6: Make necessary pointer changes after deletion.
STEP 7 : Display the contents of the list.
.
PROGRAM
#include<iostream.h>

using namespace std;

class Sort

Private:

int A[10];

int n;

public:

void get_data();

void Insert_sort();

void display();

};

void Sort::Insert_sort()

9
int i,j,temp;

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

temp=A[i];

j=i-1;

while((i>=0)&&(A[j]>temp))

A[j+1]=A[j];

j=j-1;

A[j+1]=temp;

Void Sort::get_data()

cout<<”\n How many elements are there?”;

cin>>n;

cout<<”\n Enter the elements\n”;

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

cin>>A[i];

void Sort::display()

cout<<”\n The sorted list of elements is…\n”;

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

cout<<”\n “<<A[i];

void main()

10
{

Sort obj;

cout<<”\n\t\t Insertion Sort”;

obj.get_data();

obj.Insertion_sort();

obj.display();

OUTPUT

Insertion Sort

How many elements are there?7

Enter the elements

The sorted list of elements is…

RESULT
Thus the program for implementation of Insertion and Heap sort was executed
successfully.

11
Ex.No : 5 IMPLEMENTATION OF GRAPH TRAVERSAL USING

Date : BREADTH FIRST SEARCH

AIM
To write a C++ program to perform Graph Traversal using BFS.

ALGORITHM

STEP 1 : SET STATUS = 1 (ready state) for each node in G


STEP 2 : Enqueue the starting node A and set its STATUS = 2 (waiting state)
STEP 3: Repeat Steps 4 and 5 until QUEUE is empty
STEP 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).
STEP 5: Enqueue all the neighbours of N that are in the ready state (whose STATUS = 1) and
set their STATUS = 2
(waiting state)

[END OF LOOP]

PROGRAM

#include<iostream.h>

#include<ctype.h>

#define size 20

#define TRUE 1

#define FALSE 0

Using namespace std;

Class Gbfs

Private:

int g[size][size],v1,v2;

int visit[size],Q[size];

int front,rear;

12
public:

int n;

Gbfs();

Void error(char*);

Void create(),bfs(int);

Void display();

~Gbfs();

};

THE CONSTRUCTOR DEFINED

Gpfs::Gbfs()

For(v1=0;v1<size;v1++)

For(v2=0;v2<size;v2++)

G[v1][v2]=FALSE;

For(v1=0;v1<size;v1++)

Visit[v1]=FALSE;

/*

The destructor defined

*/

Gbfs::~Gbfs()

for(v1=0;v1<size;v1++)

for(v2=0;v2<size;v2++)

g[v1][v2]=FALSE;

for(v1=0;v1<size;v1++)

13
visit[v1]=FALSE;

/*

The display defined

*/

Void Gbfs::display()

for(v2=0;v2<n;v1++)

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

count<<””<<g[v1][v2];

count<<endl;

/*

The error function

*/

Void Gbfs::error(char*Msg)

count<<”\n”<<Msg;

count<<”Press any key to abort\n”;

getch();

exit(1);

/*

The create function

*/

Void Gbfs::create()

14
{

int ch,flag;

flag=TRUE;

n=0;

cout<<”\n\t\t This is a program To Create a Graph”;

cout<<”\n\t\t The Display Is In Breadth First Manner”;

ch=toupper(getche());

if(ch==’D’)

flag=FALSE;

cout<<”enter total number of vertices\n”;

cin>>n;

do

Cout<<”\nEnter the Edge of a graph”;

cout<<”(And for termination type-99)\n”;

cin>>v1>>v2;

if(v1==-99)

break;

if(v1>=size||v2>=size)

error(“Invalid Vertex Value\n”);

else

g[v1][v2]=TRUE;

if(flag)

g[v2][v1]=TRUE;

}while(1);

/*

The bfs function

15
*/

Void Gbfs::bfs(int v1)

Int v2;

visit[v1]=TRUE;

front=rear=-1;

Q[++rear]=v1;

While(front!=rear)

V1=Q[++front];

cout<<”\n”<<v1;

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

if(g[v1][v2]==TRUE&&visit[v2]==FALSE)

Q[++rear]=v2;

visit[v2]=TRUE;

/*

The main function

*/

int main()

int v1;

Gbfs gr;

16
Gr.create();

cout<<”The Adjacency Matrix for the graph is”<<endl;

gr.display();

cout<<”Enter the Vertex from which you want to traverse”;

cin>>v1;

if(v1>==size)

gr.error(“Invalid Vertex\n”);

cout<<”The Breadth First Search of the Graph is\n”;

gr.bfs(v1);

return(0);

OUTPUT
This is a program to create a graph

The Display is Breadth First Manner

Pres sd/D for directed and u/U for undirected graph

enter total number of vertices

Enter the Edge of a graph(And for termination type-99)

01

Enter the edge of a graph(And for termination type-99)

02

Enter the edge of a graph(And for termination type-99)

13

Enter the edge of a graph(And for termination type-99)

23

Enter the edge of a graph(And for termination type-99)

17
-99 -99

The Adjacency Matrix for the graph is

0110

1001

1001

0110

Enter the vertex from which you want to traverse 0

The Breadth First Search of the Graph is

RESULT

Thus the program for Graph Traversal using BFS was executed successfully.

18
Ex.No : 6
IMPLEMENTATION OF GRAPH TRAVERSAL USING DEPTH
Date : FIRST SEARCH

AIM
To write a C++ program to implement Graph Traversal using DFS

ALGORITHM

STEP 1: SET STATUS = 1 (ready state) for each node in G

STEP 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)

STEP 3: Repeat Steps 4 and 5 until STACK is empty

STEP 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)

STEP 5 : Push on the stack all the neighbors of N that are in the ready state (whose STATUS
= 1) and set their STATUS = 2 (waiting state)

[END OF LOOP]

STEP 6: EXIT

PROGRAM

//list of include files

#include<iostream>

#include<ctype.h>

Using namespace std;

#define MAX 20;

#define TRUE 1

#define FALSE 0

//Global declarations

//Declare an adjancency matrix for storing the graph

Class Gdfs

Private:

Int g[MAX][MAX],v[MAX];

19
Int v1,v2;

Public:

Int n;

Gdfs();

Vod error(char*);

Void create(),display();

Void Dfs(int);

~Gdfs();

};

/*

……………………………………………………………………………………………………
…………………………………………………………....The constructor defined

……………………………………………………………………………………….....................
.........................................................

*/

Gdfs::Gdfs()

for(v1=0; v1<MAX; v1++)

V[v1]=FALSE;

for(v1=0; v1<MAX; v1++)

for(v2=0;v2<MAX; v2++)

g[v1][v2]=FALSE

/*

……………………………………………………………………………………………………
………………………………………………………….

The destructor defined

……………………………………………………………………………………………………
…………………………………………………………

*/

20
Gdfs::~Gdfs()

*/

for(v1=0; v1<MAX; v1++_)

for(v2=0; v2<MAX; v2++)

g[v1][v2]=FALSE;

for(v1=0; v1<MAX; v1++)

v[v1]=FALSE;

/*

……………………………………………………………………………………………………
……………………………………………………………

The display function

……………………………………………………………………………………………………
………………………………………………………….

*/

void Gdfs::display()

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

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

cout<<””<<g[v1][v2];

cout<<endl;

21
/*…………………………………………………………………………………………………
………………………………………………………….

The error function

……………………………………………………………………………………………………
………………………………………………………….

*/

void Gdfs::error(char*Msg)

cout<<Msg;

cout<<”press any key to abort\n”;

getch();

exit(1);

/*

……………………………………………………………………………………………………
…………………………………………………………….

The create fuction

……………………………………………………………………………………………………
…………………………………………………………

*/

void Gdfs::create()

Int ch,v1,v2,Undirected;

Undirected=TRUE;

n=0;

cout<<”/n This program is for creation of graph”;

cout<<”\n And the displayed by Depth for search”;

cout<<”/n\t Press d/D for directed nad u/U for nondirected graph\n”;

Ch=toupper(getche()):

22
If(Ch==’D’)

Undirected=FALSE;

cout<<”enter total num,ber of vertices \n”;

cin>>n;

do

{
cout<<”\n Enter the edges of a graph by two vertices \n”;

cout<<”(and type -99 terminate)/n”;

cin>>v1>>v2;

if(v1==-99)

break;

if(v1>=MAX||v2>=MAX)

error(“”invalid vertex value\n”);

else

g[v1][v2]=TRUE;

if(undirected)

g[v2][v1]=TRUE:

While(1);

/*

……………………………………………………………………………………………………
……………………………………………………………

The Dfs function

……………………………………………………………………………………………………
…………………………………………………………….

*/void Gdfs::Dfs(int v1)

int v2;

23
cout<<endl<<v1;

v[v1]=TRUE;

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

if(g[v1][v2]==TRUE&&v[v2]==FALSE)

Dfs[v2];

/*

……………………………………………………………………………………………………
………………………………………………………….

The main function

……………………………………………………………………………………………………
…………………………………………………………..*/

Int main()

Gdfs gr;

Int v1;

gr.create();

cout<<The adjacency matrix for the graph is”<<endl];

gr.display();

cout<<”Enter the vertex from which you want to traverse:”;

cin>>v1;

gr,error(“invalid vertex\n”);

cout<<The Depth First Search of the Graph is “<<endl;

gr.Dfs(v1);

return 0;

OUTPUT
This Program Is For Creations Of’Graph

And The Display Is By Depth First Serach

Press d/D for directed nad u/U for undirected graph

24
U

Enter total number of vertices

Enter the edge of a graph by two vertices

(and type-99 terminate)

01

Enter the edge of a graph by two vertices

(and type-99 terminate)

02

Enter the edge of a graph by two vertices

(and type-99 terminate)

13

Enter the edge of a graph by two vertices

(and type-99 terminate)

23

Enter the edge of a graph by two vertices

(and type-99 terminate)

-99 -99

The Adjacency Matrix for the graph is

0110

1001

1001

0110

Enter the vertex from which you want to traverse:1

The Depth First Search of the Graph is

2 3

25
RESULT
Thus the C program to Graph Traversal using DFS and the output is verified.

26
Ex.No : 07 THE SHORTEST PATHS TO OTHER VERTICES USING

Date : DIJKSTRA’S ALGORITHM

AIM
To write a program in C the shortest paths to other vertices using dijkstra’s algorithm.

ALGORITHM

STEP 1 : Mark the ending vertex with a distance of zero. Designate this vertex as current.

STEP 2 : Find all vertices leading to the current vertex. Calculate their distances to the end.

STEP 3: Mark the current vertex as visited. ...

STEP 4 : Mark the vertex with the smallest distance as current, and repeat from step 2.

PROGRAM

#include<stdio.h>

#include<conio.h>

#define infinity 999

Int path[10];

Void main()

Int tot_nodes,I,j,cost[10][10],dist[10],s[10];

Void create(int tot_nodes,int cost[][10]);

Void Dijkstra(int tot_nodes,int cost[][10],int I, int dist[10]);

Void display(int I,int j,int dist[10]);

Clrscr();

Printf(“\n\t\t creation of graph”);

Printf(“\n Enter total number of nodes”);

Scanf(“%d”&tot_nodes);

Create(tot_nodes,cost);

27
For(i=0;i<tot_nodes,i++)

Printf(“\n\t\t\t press any key to continue…”);

Printf(“\n\t\t When Source=%d\n”,i);

For(j=0;j<tot_nodes,j++)

Dijkstra(tot_nodes,cost,I,dist);

If(dist[j]==infinity)

Printf(“\n there is np path to 5d\n”,j);

Else

Display(I,j,dist);

Void create(ont tot_nodes,int cost[][10])

Int I,j,val,tot_edges,count=0;

For(i=o;I<tot_nodes;i++)

For(j=0;j<tot_nodes;j++)

If(i==j)

Cost[i][j]=0;//diagonal elements are o

else

cost[i][j]=infinity;

28
}

Printf(“\n Total number of edges”);

Scanf(“%d”,&tot_edges);

While(count<tot edges)

Printf(“\n Enter Vi and Vj”);

Scanf(“%d%d”,&i&j);

Printf(“\n Enter the cost along this edge”);

Scanf(“%d”,&val);

Cost[j][i]=val;

Cost[i][j]=val;

Count++;

Void dijkstra(int tot_nodes,int cost[10][10],int source,Int dist[p])

int I,j,v1,v2,min_dist;

int s[10];

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

Dist[i]=coswt[source][i];//initially put the

S[i]=-0;//distance from source vertax put to i

//i is varied for each vertax

Path[i]=source;//all the sources are put in path

S[source]=1;

For(i=1;j<tot_nodes;i++)

29
Min_dist=infinity;

V1=-1;//reset previous value of v1

For(j=o;j<tot_nodes;j++)

If(s[j]==0)

If(dist[j]<min_dist)

Min_dist=dist[j];//finding minimum distance

V1=j;

S[v1]=1;

For(v2=0;v2<tot_nodes;v2++)

If(s[v2]==0

If(dist[v1]+cost[v1][v2]<dist[v2])

dist[v2]=dist[v1]+cost[v1][v2];

path[v2]=v1;

Void display (int source,int destination, int dist[])

30
int i;

getch();

printf(“\n step by step shortest path is …\n”);

for(i=destination :i!=source;i=path[i])

Printf(“%d<-“,i);

Printf(“%d”,i);

Printf(“the length=%d”,dist[destination]);

OUTPUT

Creation of graph

Enter total number of nodes 5

Total number of edges 7

Enter Vi and Vj 0 1

Enter the cost along this edge 4

Enter Vi and Vj 0 2

Enter the cost along this edge 8

Enter Vi and Vj 1 2

Enter the cost along this edge 1

Enter Vi and Vj 1 3

Enter the cost along this edge 3

Enter Vi and Vj 2 3

Enter the cost along this edge 7

Enter Vi and Vj 2 4

Enter the cost along this edge 3

31
Enter Vi and Vj 3 4

Enter the cost along this edge 8

Press any key to continue..

When source=0

Step by step shortest path is…

0 the length=0

Step by step shortest path is…

1<-0 the length=4

Step by step shortest path is…

2<-1<-0 the length=5

Step by step shortest path is…

3<-1<-0 the length =7

Step by step shortest path is…

4<-2<-1<-0 the length =8

Press any key to continue…

When source=1

Step by step shortest path is…

0<-1 the length =4

Step by step shortest path is…

1 the length=0

Step by step shortest path is…

2<-1 the length=1

Step by step shortest path is…

3<-1 the length=3

Step by step shortest path is…

4<-2<-1 the length =4

Press any key to continue…

When source=2

32
Step by step shortest path is…

0<-1<-2 the length=5

Step by step shortest path is…

1<-2 the length =1

Step by step shortest path is…

2 the length=0

Step by step shortest path is…

3<-1<-2 the length=4

Step by step shortest path is…

4<-2 the length=3

Press any key to continue…

When source=3

Step by step shortest path is…

0<-1<-3 the length =7

Step by step shortest path is…

1<-3 the length=3

Step by step shortest path is…

2<-1<-3 the length=4

Step by step shortest path is…

3 length=0

Step by step shortest path is…

4<-2<-1<-3 the length=7

Press any key to continue…

When source=4

Step by step shortest path is…

0<-1<-2<-4 the length=8

Step by step shortest path is…

1<-2<-4 the length=4

33
Step by step shortest path is…

2<-4 the length=3

Step by step shortest path is…

3<-1<-2<-4 the length=7

Step by step shortest path is…

4 the length=0

RESULT

Thus, the program for paths to other vertices using dijkstra’s algorithm was executed
successfully

34
Ex.No : 8
UNDIRECTED GRAPH USING PRIM’S ALGORITHM
Date :

AIM
To write a program in C++ for undirected graph using prim’s algorithm algorithm.

ALGORITHM

STEP 1: Select a starting vertex.

STEP 2: Repeat Steps 3 and 4 until there are fringe vertices.

STEP 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum
weight.

STEP 4: Add the selected edge and the vertex to the minimum spanning tree T.

[END OF LOOP]

STEP 5: EXIT.

PROGRAM

#include<iostream>

#define SIZE 20

#define INFINITY 32767

Using namespace std;

Class MST

Private:

Int G[SIZE][SIZE],nodes;

Public:

MST();

Void prim();

Void get_data();

};

/* this function finds the minimal spanning tree by prim’s algorithm */


35
MST::MST()

For(int i=0;i<SIZE;i++) // Initialize the graph

For(int j=0;j<SIZE;j++)

G[i][j]=0;

Void MST::Prim()

Int select[SIZE],I,j,k;

Int min _dist,v1,v2,total=0;

For(i=0;i<nodes;i++) // initialize the selected vertices list

Select[i]=0;

Cout<<”\n\n the minimal spanning tree Is:\n”;

Select[0]=1;

For(k=1;k<nodes;k++)

Min_dist=INFINITY;

For(i=0;i<nodes;i++) //select an edge such that one vertex ,is

{ //selected and other is not and the edge

For(j=0;j<nodes;j++) //has the least weight.

If G[i][j]&& ((select[i]&&(select[j])||(!select[i]&&select[j])))

If(G[i][j]<min_dist)//obtained edge with minimum Wt

Min_dist=G[i][j];

V1=j;

V2=j;//picking up those vertices

36
}

Cout<<”\n Edge(“<<v1<<””<<v2<<”) and weight=”<<min_dist;

Select[v1]=select[v2]=1;

Total=total+min_dist;

Cout<<”\n\n\t Total path length Is=”<<total;

Void MST::get_data()

Int v1,v2,length,n;

Cout<<”\n Enter Numder of Nodes in the Graph”;

Cin>>nodes;

Cout<<”\n Enter Number of Edges in The Graph”;

Cin>>n;

//entering weighted graph

Cout<<”\n Enter edges and weights\n”;

For(int i=0;i<n;i++)

Cout<<”\n Enter Edge by v1 and v2:”;

Cin>>v1>>v2;

Cout<<”\n Enter corresponding weight:”;

G[v1][v2]=G[v2][v1]=length;

Int main()

37
{

MSTobj;

Cout<<’\n\t prim’s Algorithm\n”;

Obj.get_data();

Cout<<”\n\t”;

Obj.Prim();

return 0;

OUTPUT

Prim’s Algorithm

Enter Number of Nodes in The Graph 7

Enter Number of Edges in The Graph 9

Enter edges and weights

Enter edges by v1 and v2:0 1

Enter corresponding weight:27

Enter Edge by v1 and v2:1 2

Enter corresponding weight:16

Enter Edge by v1 and v2:2 3

Enter corresponding weight:12

Enter Edge by v1 and v2:3 4

Enter corresponding weight:22

Enter Edge by v1 and v2:4 5

Enter corresponding weight:25

Enter Edge by v1 and v2:0 5

Enter corresponding weight:6

Enter Edge by v1 and v2:1 6

38
Enter corresponding weight:14

Enter Edge by v1 and v2:4 6

Enter corresponding weight:24

Enter Edge by v1 and v2:3 6

Enter corresponding weight:18

The minimal spanning tree is:

Edge(0 5) and weight=6

Edge(4 5)and weight=25

Edge(3 4)and weight=22

Edge(2 3)and weight=12

Edge(1 2)and weight=16

Edge(1 6)and weight=14

Total path length is =95

RESULT

Thus, the program for undirected graph using prim’s algorithm algorithm was executed
successfully

39
Ex.No : 09 IMPLEMENTATION OF IMPLEMENT FLOYD’S
Date : ALGORITHM

AIM
To write a C program for the Implementation of Floyd’s Algorithm.

ALGORITHM

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]).

PROGRAM

#include<stdio.h>

include<conio.h>

void main()

Int wt[10][10],n,I,j;

Void Floyd_shortest_path(int matrix[10][10],int n;

crscr();

printf(“\n create a graph using adjacenty matrix”);

printf(“\n\n How many vertices are there?”);

scanf(“%d”,&n);

printf(“\n Enter the elements”);

printf(“\n[Enter 999 as infinity value]”);

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

40
{

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

Priontf(“\nwt[%d][%d]”,I,j);

Scanf(“%d”,&wt[i][j]);

Printf(“\n\t Computing All pair shortest path…\n”);

Floyd_shortest_path(wt,n);

Getch();

Void Floyd_shortest_path(intwt[10][10],int n)

Int D[5][10][10],I,j,k;

Int min(int,int);

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

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

D[0][i][j]=wt[i][j];

/*

Printing D(K)

*/

For(k=0;k<=n;k++)

Printf(“R(%d)=\n”,k);

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

41
{

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

Printf(“%d”,D[k][i][j]);

Printf(“\n”);

Int min(int a,int b)

If(a<b)

Return a;

Else

Return b;

OUTPUT

Create a graph using adjacency matrix

How many vertices are there?3

Enter the elements[Enter 999 as infinity value]

Wt[1][1]0

Wt[1][2]8

Wt[1][3]5

Wt[2][1]2

Wt[2][2]0

Wt[2][3]999

Wt[3][1]999

42
Wt[3][2]1

Wt[3][3]0

RESULT

Thus, the program for Implementation of Floyd’s Algorithm was executed successfully.

43
Ex.No : 10
DIRECTED GRAPH USING WARSHALL'S ALGORITHM
Date :

AIM

To write a C program to implement Directed Graph Using Warshall's Algorithm


.
ALGORITHM

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]).

PROGRAM

# include<stdio.h>

#include<conio.h>

Void main()

Int matrix[10][10],n,i,j;

Void Warshall(int matrix[10][10],int n);

Clrscr();

Printf(“\nCreate a graph using adjacency matrix”);

Printf(“\n\n How many vertices are there ?”);

Scanf(“%d”,&n);

Printf(“\n Enter the elements”);

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

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

44
{

Printf(“\nmatrix[%d][%d]”,i,j);

Scanf(“%d”,&matrix[i][j]);

Printf(“\n\tComputing Transitive closure …\n”);

Warshall(matrix,n);

getch();

Void Warshall(int matrix[10][10],int n)

int R[5][10][10],i,j,k;

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

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

R[0][i][j]=matrix[i][j];//computing R(0)

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

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

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

R[k][i][j]=R[k-1][i][j]||(R[k-1][i][k]&&R[k-1][k][j]);

45
}

/*

printing R(k)

*/

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

printf(“R(%d)=\n”,k);

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

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

printf(“\n”);

printf(“\n”);

OUTPUT

Create a graph using adjacency matrix

How many vertices are there? 4

Enter the elements Input graph will be

matrix[1][1]0
a b

matrix[1][2]1

matrix[1][3]0
c d
46
matrix[1][4]0

matrix[2][1]0

matrix[2][2]0

matrix[2][3]0

matrix[2][4]1

matrix[3][1]0

matrix[3][2]0

matrix[3][3]0

matrix[3][4]0

matrix[4][1]1

matrix[4][2]0

matrix[4][3]1

matrix[4][4]0

…Computing Transitive closure…

R(1)=

0100

0001

0000

1110

R(2)=

0101

0001

0000

1111

R(3)=

0101

0001

47
0000

1111

R(4)=

1111

1111

0000

1111

RESULT

Thus the C programs to i implement Directed Graph Using Warshall's Algorithm


was executed successfully and output is verified.

48
Ex.No : 11 IMPLEMENTATION OF THE DIVIDE AND CONQUER

Date : TECHNIQUE

AIM
To write a C++ program to implement Divide and Conquer Technique.

ALGORITHM

STEP 1: Divide: Break the given problem into sub problems of same type. This step
involves breaking the problem into smaller sub-problems. ...

STEP 2 : Conquer: Recursively solve these sub-problems. ...

STEP 3 : Combine: Appropriately combine the answers.

PROGRAM
#include <iostream>

#include<climits>

Using namespace std;

Void min_max(int a[],int low ,int high ,int&min ,int&max)

If(low==high)//only one element in the list

If(max < a[low])

Max = a[low];

If (min > a[high])

Min = a[high];

Return;

49
}

If(high- -low== 1)//tow element in the list

If(a[low] < a[high])

{
if(min >a[low])

Min= a[low];

If(max < a[high]

Max = a[high];

Else {

if (min >a[high])

Min = a[high];

If(max < a[low])

Max = a[low];

Return:

Int mid = (low +high) /2;

Min_ Max(a, low, mid, min, max);

Min _Max(a, mid +1,high, min ,max);


50
}

Int main()

int a[20],n;

int max, min;

Cout<<”\n how many element are there>?”;

Cin>>n;

For(int i=0;i<n;i++)

Cout<<”enter tha element:”;

Cin>>a[i];

Max = a[0];

Min = a[0];

Min max (a,0,n- 1,min,max);

Cout<<”Tha minimum array element is”<< min<< end1;

Cout <<”Tha maximum array elememt is”<<max<<end1;return 0;

OUTPUT

How many element are there? 5

Enter the element: 30

Enter the element: 10

Enter the element: 40

Enter the element : 50

Enter the element: 20

The minimum array element is 10

The maximum array element is 50

51
RESULT

Thus, the program for implementation of Divide and Conquer Technique

executed successfully.

52
Ex.No : 12 IMPLEMENTATION OF MERGE SORT AND QUICK SORT

Date : METHODS

AIM
To write a C program to implement Merge Sort And Quick Sort Methods

ALGORITHM

STEP 1: Pick: Select an element.

STEP 2: Divide: Split the problem set, move smaller parts to the left of the pivot and larger
items to the right.

STEP 3: Repeat and combine: Repeat the steps and combine the arrays that have previously
been sorted.

PROGRAM

MERGE SORT :

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

class MS

private:

int A[10];

public:

int n;

int low,high;

void get_data();

void MergeSort(int low,int high);

void Combine(int low,int mid,int high);

53
void Display();

void MS::get_data()

cout<<”\n Enter the length of list:”;

cin>>n;

cout<<”\n Enter list elements:\n”;

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

cin>>A[i];

void MS::MergeSort(int low,int high)

int mid;

if(low<high)

mid=(low+high)/2;

MergeSort(low,mid);

MergeSort(mid+1,high);

Combine(low,mid,high)l

void MS::Combine(int low,int mid,int high)

int I,j,k;

int temp[10];

k=low;

i=low;

j=mid+1;

54
while(i<=mid&&j<=high)

if(A[i]<=A[j])

temp[k]=A[i];

i++;

k++;

else

temp[k]=A[j];

i++;

k++;

while(i<=mid)

temp[k]=a[i];

i++;

k++;

}
}

while(i<=high)

temp[k]=a[j];

j++;

k++;

}
55
for(k=low;k<=high;k++)

A[k]=temp[k];

Void MS::display()

Count<<”\n\n the sorted array is….\n”;

Void main()

MS obj;

Clrscr();

Count<<”\n\t\t merge sort \n”;

obj.get data();

obj.low=0;

obj.high=obj.n-1;

obj.mergeSort(obj.low,obj.high);

obj.display();

getch()

OUTPUT

Enter the length of list:7

70

20

30

40

10

50
56
60

The sorted array is……

10 20 30 40 50 60 70

QUICK SORT :

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

#define SIZE 10

Class quick

Private:

Int arr[SIZE];

Public:

int get_data(int);

void quicksort(int,int);

int partition(int,int);

void swap(int,int);

void display(int);

};

int Quick::get_data(int n)

Int i;

Cout<<”\n Enter Total numbers to sort:”;

Cin>>n;

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

Cout<<”\nEnter Element”;

57
Cin>>arr[i];

return n;

Void Quick::quicksort(int p,int q)

int j;

if(p<q)

j=partition(p,q+1);

quicksort(p,j-1);

quicksort(j+1,q);

int Quick::partition(int m,int p)

Int pivot=arr[m];

Int i=m,j=p;

do

do

i++;

}while(arr[i]<pivot);

do

j--;

}while(arr[j]>pivot);

58
If(i<j)

Swap(i,j);

}while(i<j);

arr[m]=arr[j];

arr[j]=pivot;

return j;

Void quick::swap(int i, int j)

Int p;

P=arr[i];

arr[i]=arr[j];

arr[j]=p;

Void quick::display(int n)

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

cout<<” “<<arr[i];

Void main()

Quick obj;

int n,i;

Clrscr();

Cout<<”\n\t\t quick sort method \n”;

n= obj.get_data(n);

obj.quicksort(0,n-1);

cout<<”\n\n\t sorted array is :\n”;

59
obj.display(n);

getch();

OUTPUT:

Enter total numbers to sort : 5

Enter Element 30

Enter Element 50

Enter Element 10

Enter Element 20

Enter Element 40

Sorted Array is:

10 20 30 40 50

RESULT
Thus the C program to implement Merge Sort And Quick Sort Methods was executed
successfully and output is verified.

60
Ex.No : 13
IMPLEMENTATION OF N QUEENS PROBLEM USING
Date : BACKTRACKING

AIM
To write a C program to implement 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<conio.h>

#include<math.h>

#include<process.h>

int board[20];

int count;

void main()

61
int n,i,j;

void Queen(int row,int n);

clrscr();

printf(“\n\t program for n-Queen’s using backtracking”);

printf(“\nEnter Number of Queen’s”);

scanf(“%d”,&n);

Queen(1,n);

getch();

Void print_board(int n)

int i,j;

Print(“\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++)

If(board[i]==j)

Printf(“\tQ”);

else

printf(“\t-“);

62
Printf(“\n press any key to continue….”0;

getch();

int place(int row,int column)

int i;

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

if(board[i]==column)

return 0;

else

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

return 0;

Return 1;

void Queen(int row,int n)

int column;

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

if(place(row,column));

Board[row]=column;

If(row==n)

Print_board(n);

else

Queen(row+1,n);

63
}

OUTPUT
Program for n-Queen’s Using Backtracing

Enter Number of Queen’s 4

Solution 1:

1 2 3 4

1 - Q - -

2 - - - Q

3 Q - - -

4 - - Q -

Press any key to continue…

Solution 2:

1 2 3 4

1 - - Q -

2 Q - - -

3 - - - Q

4 - Q - -

RESULT

Thus the C program to implement N Queens Problem Using Backtracking


was executed successfully and output is verified.

64
Ex.No : 14 IMPLEMENTATION OF TRAVELING SALESPERSON

Date : PROBLEM

AIM
To write a C program to implement Traveling Salesperson Problem
ALGORITHM

Step 1. Population initialization: use the city number to encode the TSP path and randomly
generate the arrangement order of cities.
Step 2. Calculate the fitness value of each individual in the population.
Step 3. Randomly select the predator and prey population, and then randomly rearrange the
position of prey population.
Step 4. Calculate the scale factor R of biological interaction velocity.
Step 5. Determination of active individuals M in predator population by binary integer
mapping.
Step 6. Mutation: calculate the location X of biological interaction, i.e., the visit route of the
traveler.
Step 7. Crossover: if the active individual mapping is greater than 0, update the path to the
predator location; otherwise, keep the original location unchanged.
Step 8. Reselection of predator and prey populations.
Step 9. Judge whether the termination conditions are met. If so, stop the algorithm update and
output the optimal position and optimal function value, that is, the shortest route and shortest
path value of TSP. Otherwise, return to Step 2.

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];
}
temp = matrix[c][count];
nearest_city = count;
}

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

66
return 0;
}

OUTPUT

The Optimal path…


0->1->2->4->3->0
The Optimal Cost of the tour is : 37
The Approximate path is
0->1->2->3->4->0
The Approximate minimum Cost of the tour is:39
The error in Approximation is =2 units

RESULT
Thus the C program to implement Traveling Salesperson Problem was executed
successfully and output is verified.

67
Ex.No : 15
IMPLEMENTATION OF RANDOMIZED ALGORITHMS FOR
Date : FINDING THE Kth SMALLEST NUMBER

AIM
To write a C++ program to Finding The Kth Smallest Number

ALGORITHM

STEP 1: First find the pivot point or partition_index (pat_index) using quick sort’s
partition method.

STEP 2: pat_index or pivot is a position that partitions the list into two parts: every element
on the left is less than the pivot and every element on the right is more than the pivot).

STEP 3: The algorithm recurs only for the part that contains the k-th smallest element.

STEP 4: If the index of the partitioned element (pivot) is more than k, then the algorithm
recurs for the left part.

STEP 5: If the index (pivot) is same as k, then we have found the k-th smallest element and
it is returned.

STEP 6: If index is less than k, then the algorithm recurs for the right part.

PROGRAM

#include<iostream>

#include<random>

using namespace std;

#define infinity 9999

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

int kthSmallest(int arr[],int low,int high,int K)

//If K is smaller than number of elements in array

68
if(K>0&&K<=high-low+1)

int pos = partition(arr,low,high);

if(pos-low==K-1)//Element is found at the pos

return arr[pos];

if(pos-low>K-1)

return kthSmallest(arr,low,pos-1,K);//scan left sublist

return kthSmallest(arr,pos+1,high,k-pos+low-1);//scan right sublist

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

return infinity;

void swap(int*a,int b)

int temp=*a;

*a=*b;

*b=temp;

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

int range=(high-low)+1;//find the random index from the range of low to //high

int rand_index=(rand() % range)+low;//Finding randomfrom the range of low //to


high

swap(&arr{rand_index],&arr[high]);

int pivot_element=arr[high],i=low;

for(int j=low;j<=high-1;j++)

if(arr[j]<=pivot_element)

{
69
swap(&arr[i],&arr[j]);

i++;

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

return I;//index at which position pivot occupies its position

int main()

int arr[]={4,6,2,1,5,3};

int N=sizeof(arr0/sizeof(arr[0]);

int K;

cout<<”Enter the value of K:”;

cin>>K ;
cout<<”Kth smallest element is”;

cout<<kthSmallest(arr,0,N-1,K);

return 0;

OUTPUT

Enter the value of K: 3

K th Smallest element is 3

RESULT
Thus the program to Finding The Kth Smallest Number was executed successfully.

70

You might also like