CS3401- Algorithm lab Manual
CS3401- Algorithm lab Manual
Certified that this is bonafide record of work done by the above student during the year
20 -20
GRAPH ALGORITHMS
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
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 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
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;
Cin>>n;
For(int i=0;i<n;i++)
Cin>>a[i];
ruturn n;
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;
n=obj.get_value();
cin>>key;
obj.high=n-1;
ans=obj.binsearch(key,obj.low,obj.high);
if(ans!=-1)
else
OUTPUT
10
20
30
40
50
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
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<string.h>
int n,m;
void main()
Char Txt[50],Pat[50];
int i,j;
gets(Txt);
gets(Pat);
7
n=strien(Txt);
m=strien(Pat);
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
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>
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()
cin>>n;
for(int i=0;i<n;i++)
cin>>A[i];
void Sort::display()
for(int i=0;i<n;i++)
cout<<”\n “<<A[i];
void main()
10
{
Sort obj;
obj.get_data();
obj.Insertion_sort();
obj.display();
OUTPUT
Insertion Sort
RESULT
Thus the program for implementation of Insertion and Heap sort was executed
successfully.
11
Ex.No : 5 IMPLEMENTATION OF GRAPH TRAVERSAL USING
AIM
To write a C++ program to perform Graph Traversal using BFS.
ALGORITHM
[END OF LOOP]
PROGRAM
#include<iostream.h>
#include<ctype.h>
#define size 20
#define TRUE 1
#define FALSE 0
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();
};
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;
/*
*/
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;
/*
*/
Void Gbfs::display()
for(v2=0;v2<n;v1++)
for(v2=0;v2<n;v2++)
count<<””<<g[v1][v2];
count<<endl;
/*
*/
Void Gbfs::error(char*Msg)
count<<”\n”<<Msg;
getch();
exit(1);
/*
*/
Void Gbfs::create()
14
{
int ch,flag;
flag=TRUE;
n=0;
ch=toupper(getche());
if(ch==’D’)
flag=FALSE;
cin>>n;
do
cin>>v1>>v2;
if(v1==-99)
break;
if(v1>=size||v2>=size)
else
g[v1][v2]=TRUE;
if(flag)
g[v2][v1]=TRUE;
}while(1);
/*
15
*/
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;
/*
*/
int main()
int v1;
Gbfs gr;
16
Gr.create();
gr.display();
cin>>v1;
if(v1>==size)
gr.error(“Invalid Vertex\n”);
gr.bfs(v1);
return(0);
OUTPUT
This is a program to create a graph
01
02
13
23
17
-99 -99
0110
1001
1001
0110
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 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
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
#include<iostream>
#include<ctype.h>
#define TRUE 1
#define FALSE 0
//Global declarations
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()
V[v1]=FALSE;
for(v2=0;v2<MAX; v2++)
g[v1][v2]=FALSE
/*
……………………………………………………………………………………………………
………………………………………………………….
……………………………………………………………………………………………………
…………………………………………………………
*/
20
Gdfs::~Gdfs()
*/
g[v1][v2]=FALSE;
v[v1]=FALSE;
/*
……………………………………………………………………………………………………
……………………………………………………………
……………………………………………………………………………………………………
………………………………………………………….
*/
void Gdfs::display()
cout<<””<<g[v1][v2];
cout<<endl;
21
/*…………………………………………………………………………………………………
………………………………………………………….
……………………………………………………………………………………………………
………………………………………………………….
*/
void Gdfs::error(char*Msg)
cout<<Msg;
getch();
exit(1);
/*
……………………………………………………………………………………………………
…………………………………………………………….
……………………………………………………………………………………………………
…………………………………………………………
*/
void Gdfs::create()
Int ch,v1,v2,Undirected;
Undirected=TRUE;
n=0;
cout<<”/n\t Press d/D for directed nad u/U for nondirected graph\n”;
Ch=toupper(getche()):
22
If(Ch==’D’)
Undirected=FALSE;
cin>>n;
do
{
cout<<”\n Enter the edges of a graph by two vertices \n”;
cin>>v1>>v2;
if(v1==-99)
break;
if(v1>=MAX||v2>=MAX)
else
g[v1][v2]=TRUE;
if(undirected)
g[v2][v1]=TRUE:
While(1);
/*
……………………………………………………………………………………………………
……………………………………………………………
……………………………………………………………………………………………………
…………………………………………………………….
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];
/*
……………………………………………………………………………………………………
………………………………………………………….
……………………………………………………………………………………………………
…………………………………………………………..*/
Int main()
Gdfs gr;
Int v1;
gr.create();
gr.display();
cin>>v1;
gr,error(“invalid vertex\n”);
gr.Dfs(v1);
return 0;
OUTPUT
This Program Is For Creations Of’Graph
24
U
01
02
13
23
-99 -99
0110
1001
1001
0110
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
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 4 : Mark the vertex with the smallest distance as current, and repeat from step 2.
PROGRAM
#include<stdio.h>
#include<conio.h>
Int path[10];
Void main()
Int tot_nodes,I,j,cost[10][10],dist[10],s[10];
Clrscr();
Scanf(“%d”&tot_nodes);
Create(tot_nodes,cost);
27
For(i=0;i<tot_nodes,i++)
For(j=0;j<tot_nodes,j++)
Dijkstra(tot_nodes,cost,I,dist);
If(dist[j]==infinity)
Else
Display(I,j,dist);
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)
else
cost[i][j]=infinity;
28
}
Scanf(“%d”,&tot_edges);
While(count<tot edges)
Scanf(“%d%d”,&i&j);
Scanf(“%d”,&val);
Cost[j][i]=val;
Cost[i][j]=val;
Count++;
int I,j,v1,v2,min_dist;
int s[10];
for(i=0;i<tot_nodes;i++)
S[source]=1;
For(i=1;j<tot_nodes;i++)
29
Min_dist=infinity;
For(j=o;j<tot_nodes;j++)
If(s[j]==0)
If(dist[j]<min_dist)
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;
30
int i;
getch();
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 Vi and Vj 0 1
Enter Vi and Vj 0 2
Enter Vi and Vj 1 2
Enter Vi and Vj 1 3
Enter Vi and Vj 2 3
Enter Vi and Vj 2 4
31
Enter Vi and Vj 3 4
When source=0
0 the length=0
When source=1
1 the length=0
When source=2
32
Step by step shortest path is…
2 the length=0
When source=3
3 length=0
When source=4
33
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 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
Class MST
Private:
Int G[SIZE][SIZE],nodes;
Public:
MST();
Void prim();
Void get_data();
};
For(int j=0;j<SIZE;j++)
G[i][j]=0;
Void MST::Prim()
Int select[SIZE],I,j,k;
Select[i]=0;
Select[0]=1;
For(k=1;k<nodes;k++)
Min_dist=INFINITY;
If G[i][j]&& ((select[i]&&(select[j])||(!select[i]&&select[j])))
Min_dist=G[i][j];
V1=j;
36
}
Select[v1]=select[v2]=1;
Total=total+min_dist;
Void MST::get_data()
Int v1,v2,length,n;
Cin>>nodes;
Cin>>n;
For(int i=0;i<n;i++)
Cin>>v1>>v2;
G[v1][v2]=G[v2][v1]=length;
Int main()
37
{
MSTobj;
Obj.get_data();
Cout<<”\n\t”;
Obj.Prim();
return 0;
OUTPUT
Prim’s Algorithm
38
Enter corresponding weight:14
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;
crscr();
scanf(“%d”,&n);
for(i=0;i<=n;i++)
40
{
For(j=1;j<=n;j++)
Priontf(“\nwt[%d][%d]”,I,j);
Scanf(“%d”,&wt[i][j]);
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”);
If(a<b)
Return a;
Else
Return b;
OUTPUT
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
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;
Clrscr();
Scanf(“%d”,&n);
For(i=1;i<=n;i++)
for (j=1;j<=n;j++)
44
{
Printf(“\nmatrix[%d][%d]”,i,j);
Scanf(“%d”,&matrix[i][j]);
Warshall(matrix,n);
getch();
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
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
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
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. ...
PROGRAM
#include <iostream>
#include<climits>
Max = a[low];
Min = a[high];
Return;
49
}
{
if(min >a[low])
Min= a[low];
Max = a[high];
Else {
if (min >a[high])
Min = a[high];
Max = a[low];
Return:
Int main()
int a[20],n;
Cin>>n;
For(int i=0;i<n;i++)
Cin>>a[i];
Max = a[0];
Min = a[0];
OUTPUT
51
RESULT
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 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();
53
void Display();
void MS::get_data()
cin>>n;
for(int i=0;i<n;i++)
cin>>A[i];
int mid;
if(low<high)
mid=(low+high)/2;
MergeSort(low,mid);
MergeSort(mid+1,high);
Combine(low,mid,high)l
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()
Void main()
MS obj;
Clrscr();
obj.get data();
obj.low=0;
obj.high=obj.n-1;
obj.mergeSort(obj.low,obj.high);
obj.display();
getch()
OUTPUT
70
20
30
40
10
50
56
60
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;
Cin>>n;
For(i=0;i<n;i++)
Cout<<”\nEnter Element”;
57
Cin>>arr[i];
return n;
int j;
if(p<q)
j=partition(p,q+1);
quicksort(p,j-1);
quicksort(j+1,q);
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;
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();
n= obj.get_data(n);
obj.quicksort(0,n-1);
59
obj.display(n);
getch();
OUTPUT:
Enter Element 30
Enter Element 50
Enter Element 10
Enter Element 20
Enter Element 40
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.
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;
clrscr();
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 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;
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
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 - -
RESULT
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;
}
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
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>
68
if(K>0&&K<=high-low+1)
return arr[pos];
if(pos-low>K-1)
return infinity;
void swap(int*a,int b)
int temp=*a;
*a=*b;
*b=temp;
int range=(high-low)+1;//find the random index from 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]);
int main()
int arr[]={4,6,2,1,5,3};
int N=sizeof(arr0/sizeof(arr[0]);
int K;
cin>>K ;
cout<<”Kth smallest element is”;
cout<<kthSmallest(arr,0,N-1,K);
return 0;
OUTPUT
K th Smallest element is 3
RESULT
Thus the program to Finding The Kth Smallest Number was executed successfully.
70