Aoa Manual
Aoa Manual
LABORATORY MANUAL
ANALYSIS OF ALGORITHM
( A. O. A. )
INDEX
THEORY:-
Insertion sort is one that sorts a records by inserting records into a existing
sorted file. In simple insertion sort, initially x[0] is thought of an sorted file of one
element. In succeeding passes one element (started with x[1]) is compared with all
elements above it. Elements which are greater than that element are shifted down by
one position, then that element is copied into empty space. Insertion sort is a simple
sorting algorithm that builds the final sorted array (or list) one item at a time. It is
much less efficient on large lists than more advanced algorithms such as quicksort,
heapsort, or merge sort.
ALGORITHM:-
Step 1: Start
Step 2: For k=1 to n-1 repeat following steps
Step 2.1: ascend x[k] to ’y’
Step 2.2: for i=k-1 to 0, if y < x[i] repeat following step
Step 2.3: x[i+1]=x[i];
Step 2.4: x[i+1]=y;
Step 3: stop
page|3
PROGRAM:-
#include<stdio.h>
#include<conio.h>
int InsertionSort(int [],int);
void main()
{
int arr[10],n,i,moves;
clrscr();
printf("Enter number of elements");
scanf("%d",&n);
printf("Enter Elements");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
moves=InsertionSort(arr,n);
printf("Array Elements after sorting");
for(i=0;i<n;i++)
printf("\t%d",arr[i]);
printf("\n%d moves were made to sort this list\n",moves);
getch();
}
int InsertionSort(int arr[],int n)
{
int i,j,k,temp,min,moves=0;
for(i=0,k=0;i<n;i++,k++)
{
for( j=i+1,min=i;j<n;j++)
if(arr[j]<arr[min])
min=j;
if(i!=min)
{
temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
} moves++;
}
return(moves);
} page|4
OUTPUT:- Enter number of elements:5
Enter the elements:
12
6
9
15
8
Array elements after sorting: 6 8 9 12 15
563 moves were made to sort this list.
THEORY:-
Merge sort follows the principle of Divide & Conquer. Merge sort is a recursive algorithm that
continuously splits a list in half. If the list is empty or has one item, it is sorted by definition (the base case).
If the list has more than one item, we split the list and recursively invoke a merge sort on both halves. Once
the two halves are sorted, the fundamental operation, called a merge, is performed. Merging is the process
of taking two smaller sorted lists and combining them together into a single, sorted, new list. The first
process is splitting. We can divide a list in half, log n times where n is the length of the list. The second
process is the merge. Each item in the list will eventually be processed and placed on the sorted list. So the
merge operation which results in a list of size n requires n operations. The result of this analysis is that log
n splits, each of which costs n for a total of nlogn operations. A merge sort is an O(nlogn) algorithm.
ALGORITHM:-
function mergesort(m)
var list left, right, result
if length(m) ≤ 1
return m
else
var middle = length(m) / 2
for each x in m up to middle - 1
add x to left
for each x in m at and after middle
add x to right
left = mergesort(left)
right = mergesort(right)
if last(left) ≤ first(right)
append right to left
return left
result = merge(left, right)
return result
function merge(left,right)
var list result
while length(left) > 0 and length(right) > 0
if first(left) ≤ first(right)
append first(left) to result
left = rest(left)
else
append first(right) to result
right = rest(right)
if length(left) > 0
append rest(left) to result
if length(right) > 0
append rest(right) to result
return result page|6
PROGRAM:-
#include <stdio.h>
#include<conio.h>
void main()
{
int x[100],n,i = 0;
clrscr();
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
printf("\nEnter the elements to be sorted: \n");
for(i = 0 ; i < n ; i++ )
{
printf("\tx[%d] = ",i);
scanf("%d",&x[i]);
}
mergesort(x, 0, n - 1);
printf("\n");
getch();
}
if(l == h)
return;
page|7
pivot = (l + h) / 2;
mergesort(arr, l, pivot);
mergesort(arr, pivot + 1, h);
merge1 = 0;
merge2 = pivot - l + 1;
else
{
arr[i + l] = temp[merge1++];
}
}
else
{
arr[i + l] = temp[merge2++];
}
}
else
{
arr[i + l] = temp[merge1++];
}
}
}
Page|8
OUTPUT:-
Enter the number of elements to be sorted: 5
Enter the elements to be sorted:
x[0] = 2
x[1] = 6
x[2] = 4
x[3] = 1
x[4] = 3
Before Mergesort: 2 6 4 1 3
After Mergesort: 1 2 3 4 6
CONCLUSION:-
EXPERIMENT NO :-2(B)
THEORY:-
Quick sort:
Quick sort is the fastest internal algorithm with the time complexity=0(n log n).The basic algorithm to sort
an array[ ] of n elements can be described recursively as follows:
1. If n<=1 ,then return
2. Pick up any element V in a[ ].This is called the pivot.
3. Apply quick sort recursively to a[ ]…….a[ j-1 ] and to a[ j+1 ]……a[ n-1 ]
Entire array will thus be sorted by as selecting an element V.
(a) Partitioning the array around V.
(b) Recursively, sorting the left partition.
(c) Recursively, sorting the right partition.
Picking a pivot:
We will choose the popular choice of the first element as the pivot. There are several strategies for
pivoting.
Partitioning:
Let the element of the array a[l],a[l+1]…..a[n-1],a[n] are to be partitioned around the pivot
V=a[l].Initial value of l will be 0 and that of n will be n-1.As recursion proceeds, these values will change.
Index of the pivot (say K) will satisfy the following conditions
K>=l
K<=n
Two cursors (Index variable) are initialized with
I=l+1 and
J=n-1
I moves towards right searching for an element greater than V. j moves towards left searching for an
element smaller than V. When these elements are found they are interchanged. Again i moves towards right
and j moves left and exchange is made necessary. The process ends when I is equal to j or i>j.
J gives the index of the pivot element after termination of the above process. page|10
Running time of Quick sort:
Running time of quick sort=running time of left partition + running time of right partition + time spent in
partitioning the elements.
T(n)=T(j) + T (n – j – 1) + cn.
ALGORITHM:-
PARTITION(int a[],int left,int right)
1. i=left
2. j=right
3. x=a[left]
4. while <- i<j
5 .while(i<=right && a[i]<=x)
6. i++;
7. while(a[j] > x)
8. j--;
9. t=a[j]
a[j]=a[left]
a[left]=t
10. void Quick_Sort(int a[],int left,int right)
11. if(left < right)
12. P=PARTITION(a,left,right)
13. Quick_Sort(a,left,P-1)
14. Quick_Sort(a,P+1,right)
page|11
ANALYSIS FOR QUICK_SORT:
Worst case:
1.Quick_sort works in worst case in two situations.
2.First if array is in increasing order.
=n(n+1)/2
=n2/2 + n/2
=n2+n
T(n) = O(n2)
Best case:
1.Quick_sort works in best case only if the partition is always at the mid-point.So that,left and right partition
will be of equal length.
=2T(n/2) + n
=2[2T(n/4)+n]+n
page|12
PROGRAM:-
#include<stdio.h>
int arr[10];
void swap(int p,int q)
{
int temp=arr[p];
arr[p]=arr[q];
arr[q]=temp;
}
void quk(int st,int end)
{
int a,b;
a=st+1;
b=end;
do
{
for(;a<=b;a++)
if(arr[st]<arr[a])
break;
for(;a<=b;b--)
if(arr[st]>arr[b])
break;
if(a<b)
swap(a,b);
}while(a<b);
swap(st,a-1);
if(st<a-2)
quk(st,a-2);
if(a<end)
quk(a,end);
}
void main()
{ page|13
int n,i,a,b,temp;
clrscr();
printf("Enter no. of element:");
scanf("%d",&n);
printf("Enter element:");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
quk(0,n-1);
printf("Array:\n");
for(i=0;i<n;i++)
printf("%d\t",arr[i]);
getch();
}
OUTPUT:-
Enter no. element:5
Enter element:12
6
9
15
8
Array:
6 8 9 12 15
EXPERIMENT NO :-03
AIM:- Write a program to implement construction of tennis tournament.
THEORY:-
To find the largest and second largest elements out of a set of n elements an algorithm that makes use
of comparison tree requires n-1 and n-2 comparisons respectively.The total no. of comparisons equals to 2n-
3.
We can improve this upper using another algorithm suggested by J.Schreier in 1952. Let us take an example
of a "Tennis Tournament" in which the players denote the values, winner denotes the largest value and
runner-up denotes the second largest value.
Theorem:
Any comparisons based algorithm that computes the largest and second largest of a set of n
unordered elements requires n-2 + [log n] comparisons.
Proof:
We know that maximum n-1 comparisons are required to find the largest element [or winner
considering the tennis tournament example] i.e n-1 is the upper bound on no. of comparisons [matches
played] and [log n] is the lower bound for no. of comparisons required.
Let us draw a directed graph corresponding to this tournament having n vertices where vertices denotes the
players and now draw a directed edges from vertex m to n if m=/=n iff either player n has defeated another
player who has defeated m.
By induction theorem any player who has played and won K matches can have maximum 2`k-1 edges
pointing into his/her node.Therefore winner needs minimum [log n] comparisons are required.
Comparisons to find winner = n-1.
Comparisons to find runner up = log n-1.
Hence total comparisons = n-1+ log n-1
= n-2+ [log n].
Where log n is the max level of the tree.
ALGORITHM:-
Page|15
PROGRAM:-
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAXELT 10001
void main()
{
int i=-1,n=0,L[MAXELT],m,s;
char t[10];
void largest_and_second_largest(int a[],int n,int *m,int *s);
clrscr();
do
{
if(i!=-1)
L[i++]=n;
else
i++;
printf("\nEnter a Number>");
gets(t);
if(sscanf(t,"%d",&n)<1)
break;
}while(1);
largest_and_second_largest(L,i,&m,&s);
printf("\nThe Maximum is %d and the Second Largest is %d",m,s);
}
void largest_and_second_largest(int a[],int n,int *m,int *s)
{
int *I,
size,
i,j,
lu,
max,
slarge,
sindex;
void swap(int *a,int *b);
size=1;
lu=-1;
I=(int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
I[i]=-1;
for(;;)
{
i=size-1;
if(i>=n)
break;
j=size+i;
if(j>=n && i!=n-1)
j=n-1;
if(j>=n)
if(lu<0)
break;
else
{
j=lu; page|16
lu=-1;
}
for(;;)
{
if(a[i]>a[j])
swap(&a[i],&a[j]);
else
I[i]=I[j];
I[j]=i;
i=j+size;
if(i>=n)
break;
else
{
j=i+size;
if(j>=n && i!=n-1)
j=n-1;
if(j>=n)
if(lu>0)
{
j=lu;
lu=-1;
}
else
{
lu=i;
break;
}
}
}
size=2*size;
}
max=a[n-1];
sindex=I[n-1];
slarge=a[sindex];
while(sindex!=-1)
{
sindex=I[sindex];
if(sindex!=-1 && a[sindex]>slarge)
slarge=a[sindex];
}
*m=max;
*s=slarge;
free(I);
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Page|17
OUTPUT:-
Enter a Number>186
Enter a Number>1896
Enter a Number>1186
Enter a Number>86
Enter a Number>-1
The maximum number is 1896 and the second number is 1186
EXPERIMENT NO :- 04
THEORY:-
Page|19
ALGORITHM:-
1.Algorithm GreedyKnapsack(m,n)
2.//p[l:n] and w[l:n] contain the profits and weights respectively
3.//of the n objects ordered such that p[i]/w[i]≥p[i+j]/w[i+1].
5.{
7.U:=m;
8.for i:=1 to n do
9.{
11.x[i]:=1.0;U:=U-w[i];
12.}
14.}
PROGRAM:-
#include <stdio.h>
#include <conio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(int i,int j)
{
return((i>j)?i:j);
}
int knap(int i,int j)
{
int value;
if(v[i][j]<0)
{
if (j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i])); page|20
v[i][j]=value;
}
return(v[i][j]);
}
void main()
{
int profit,count=0;
clrscr();
printf("\n Enter the number of elements\n");
scanf("%d",&n);
printf("\n Enter the profit and weights of the elements\n");
for(i=1;i<=n;i++)
{
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\n Enter the capacity \n");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if ((i==0)||(j==0))
v[i][j]=0;
else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
i--;
}
else
i--;
}
printf("Items included are\n");
printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit=%d\n",profit);
getch();
}
Page|21
OUTPUT:-
CONCLUSION:-
Thus the program for the knapsack problem using greedy method is implemented successfully
EXPERIMENT NO :- 05(A)
AIM:- Write A Program To Implement Minimum Cost Spanning Tree – Kruskal Algorithm.
THEORY: -
Kruskal’s Algorithm
Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree for a connected
weighted graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where
the total weight of all the edges in the tree is minimized. If the graph is not connected, then it finds a
minimum spanning forest (a minimum spanning tree for each connected component). Kruskal's algorithm is
an example of a greedy algorithm.
Description
1. Create a forest T (a set of trees), where each vertex in the graph is a separate tree.
2. Create a set S containing all the edges in the graph.
3. While S is nonempty and T is not yet spanning.
• Remove an edge with minimum weight from S
• If that edge connects two different trees, then add it to the forest, combining two trees into a single
tree, otherwise discard that edge.
4. This is a greedy algorithms approach in while every decision it makes is based on most obvious
immediate advantage.
At the termination of the algorithm, the forest has only one component and forms a minimum spanning tree
of the graph.
ALGORITHM:-
Kruskal Algorithm
1. Algorithm Kruskal(E, cost, n, t)
2. // E is a set of edges in G. n vertices in G.
3. // cost[ u, v] is cost of edge ( u, v)
4. // t is set of edges in minimum-cost spanning tree
5. //{
6. Construct a heap out of the edges costs
7. for i=1 to n do parent [i] = -1
8. //Each vertex is in a different set
9. i =0; mincost =0.0;
10. While ((i < n-1) and (heap not empty)) do
11. {
12. // Delete a minimum cost edge (u, v) from heap 13. And reheapify j
13. j= Find (u); k=Find (v)
14. if (j? k) then
15. {
16. i = i+1; page|23
17. t[ i, 1] = u; t[ i, 2] =v;
18. mincost = mincost + cost[u, v];
19. Union (j, k)
20. }
21. }
22. if(i?n-1) then write (“N0 Spamming Tree”);
23. else return mincost;
24. }
Minimum-Cost Spanning tree algorithm due to kruskal is follows:-
1. t=0;
2. while ((t has less than n-1 edges) and (E?0)) do
3. {
4. Choose an edge (v, w) from E of lowest cost.
5. Delete (v, w) from E;
6. if (v, w) does not create cycle in t then add (v, w) to t
7. else discard (v, w);
8. }
PROGRAM:-
#include<stdio.h>
#include<conio.h>
#define MAX 100
struct set_all
{
int v[20];
}set[15];
struct edge_info
{
int u,v,weight;
}edge[MAX];
int tree[MAX][3];
int n,t1;
int readedges();
void makeset();
int find(int);
void join(int,int);
void arrange_edges(int);
int spanningtree(int);
void display(int);
int readedges()
{
int i,j,k,cost;
k=1;
printf("\nEnter the no. of vertices in the Graph");
scanf("%d",&n);
printf("\n");
printf("For no edge enter 999\n");
for(i=1;i<=n;i++)
for(j=1;j<i;j++)
{
printf("weight[%d][%d]",i,j);
scanf("%d",&cost); page|24
if(cost!=999)
{
edge[k].u=i;
edge[k].v=j;
edge[k++].weight=cost;
}
}
return(k-1);
}
void makeset()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
set[i].v[j]=-1;
set[i].v[1]=i;
}
}
int find(int vertex)
{
int i,j;
for(i=1;i<=n;i++)
{
j=1;
while(set[i].v[j]!=-1)
{
if(set[i].v[j]==vertex)
return i;
j++;
}
}
return 0;
}
void join(int v1,int v2)
{
int i,j,k,l;
if(v1>v2)
{
l=v1;
v1=v2;
v2=l;
}
for(i=1;i<=n;i++)
{
j=1;
while(set[i].v[j]!=-1)
{
if(set[i].v[j]==v1)
break;
else
j++;
}
if(set[i].v[j]==v1) page|25
break;
}
for(k=1;k<=n;k++)
{
j=1;
while(set[k].v[j]!=-1)
{
if(set[k].v[j]==v2)
break;
else
j++;
}
if(set[k].v[j]==v2)
break;
}
j=1;
while(set[i].v[j++]!=-1)
j=j-1;
for(l=1;set[k].v[l]!=-1;l++)
{
set[i].v[j++]=set[k].v[l];
set[k].v[l]=-1;
}
/*else
set[v1]=v2;*/
}
void arrange_edge(int k)
{
int i,j;
struct edge_info temp;
for(i=1;i<k;i++)
for(j=1;j<=(k-1);j++)
if(edge[j].weight>edge[j+1].weight)
{
temp=edge[j];
edge[j]=edge[j+1];
edge[j+1]=temp;
}
}
int spanningtree(int k)
{
int i,sum;
arrenge_edges(k);
t1=1;
sum=0;
printf("Edges of Graph and their cost are\n");
printf("v1 v2weight\n");
for(i=1;i<=k;i++)
printf("%d %d %d\n", edge[i].u, edge[i].v, edge[i].weight);
for(i=1;i<=k;i++)
if(find(edge[i].u)!=find(edge[i].v))
{
tree[t1][1]=edge[i].u;
tree[t1][2]=edge[i].v;
sum+=edge[i].weight; page|26
join(edge[i].u,edge[i].v);
t1++;
}
return sum;
}
void display(int cost)
{
int i;
printf("\nThe edge of minimum spanning tree are\n");
for(i=1;i<t1;i++)
printf("%d\t%d\n",tree[i][1],tree[i][2]);
printf("\nThe cost of the minimum spanning tree is:%d\n",cost);
}
int main()
{
int ecount,totalcost;
clrscr();
ecount=readedge();
makeset();
totalcost=spanningtree(ecount);
display(totalcost);
getch();
return 0;
}
OUTPUT:-
weight[2][1]:2
weight[3][1]:4
weight[3][2]:999
weight[4][1]:999
weight[4][2]:5
weight[4][3]:999
weight[5][1]:999
weight[5][2]:999
weight[5][3]:4
weight[5][4]:9
weight[6][1]:999
weight[6][2]:999
weight[6][3]:999
weight[6][4]:5
weight[6][5]:4
Edges of Graph and their Costs are
v1 v2 weight
2 1 2
3 1 4
5 3 4
6 5 4
4 2 5
6 4 5
5 4 6 page|27
The edges of minimum spanning tree are
2 1
3 1
5 3
6 5
4 2
The cost of the minimum spanning tree is: 19
CONCLUSION:-
Hence we conluded that minimum cost spanning tree by kruskal algorithm is implemented
AIM:- WAP TO IMPLEMENT MINIMUM COST SPANNING TREE USING PRIM'S ALGORITHM.
THEORY:-
In the Prim's algorithm only a tree that includes only minimum-cost edge of G are included.And the
adges are added ono by one.
The next edge(i,j) that is to be added and in this i is a vertex already added and j is a vertex yet to be
included, and the cost of (i,j) is minimum among all edges(k,l) such that vertex k is the tree and
vertex l is not in the tree.
To determine the edge(i,j) efficiently,we associate each vertex j not yet included in the tree a value
near[j].
The value near[j] is a vertex in the tree such that cost[j,near[j]] is minimum among all choices for
near[j].
We define near[j]=0 for all vertices j that are already in the tree.
The next edge to include is defined to by the vertex j such that near[j]!=0(j not already in the tree) and
cost[j,near[j]] is minimum.
ALGORITHM:-
{
mincost=cost[k,l];
t[1,1]=k;
t[1,2]=l;
for i=1 tp n do
else near[i]=k;
near[k]=near[l]=0;
cost[j,near[j]] is minimum;
t[i,1]=j; page|29
t[1,2]=near[j];
mincost=mincost+cost[j,near[j]];
near[j]=0;
for k=1 to n do
then near[k]=j;
return mincost;
PROGRAM:-
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<alloc.h>
int ad[10][10],no;
void getgraph ()
int i,j,k,ne,y,wt;
clrscr();
scanf("%d",&no);
for(i=0;i<no;i++)
for(j=0;j<no;j++)
ad[i][j]=1000;
scanf("%d",&ne);
printf("\nenter edges:");
for(k=0;k<ne;k++)
y=wherey(); page|30
printf("\nfrom");
scanf("%d",&i);
gotoxy(15,y+1);
printf("to");
scanf("%d",&j);
do
gotoxy(25,y+1);
printf("weight");
gotoxy(33,y+1);
scanf("%d",&wt);
}while(wt<1);
ad[i-1][j-1]=wt;
ad[j-1][i-1]=wt;
void printad()
int i,j;
clrscr();
for(i=0;i<no;i++)
printf("\t%d",i+1);
for(i=0;i<no;i++)
printf("\n%d",i+1);
for(i=0;i<no;i++)
for(j=0;j<no;j++)
gotoxy(9+8*j,i+2);
printf("%d",ad[i][j]==1000?"0":ad[i][j]);
} page|31
}
void prims()
int i,j,min=1000,k,l,s[10],t[10][2],minwt;
for(i=0;i<no;i++)
for(j=0;j<no;j++)
if(ad[i][j]==1000||i==j)
continue;
if(ad[i][j]<min)
min=ad[i][j];
k=i;
l=j;
minwt=ad[k][l];
t[0][0]=k;
t[0][1]=l;
for(i=0;i<no;i++)
s[i]=(ad[i][k]<ad[i][l])?k:l;
s[l]=s[k]=-1;
for(i=1;i<no;i++)
j=search();
t[i][0]=j;
t[i][1]=s[j];
minwt+=ad[j][s[j]];
for(k=0;k<no;k++)
if(s[k]!=-1) page|32
s[k]=ad[k][s[k]]<ad[k][j]?s[k]:j;
s[j]=-1;
for(i=0;i<no-1;i++)
printf("%d---->%d\twt=%d\n",t[i][0]+1,t[i][1]+1,ad[t[i][0]][t[i][1]]);
int search()
int min=1000,k,t=0,s[10];
for(k=0;k<no;k++)
if((s[k]!=-1)&&min>ad[k][s[k]])
min=ad[k][s[k]];
t=k;
return(t);
void main()
int choice;
while(1)
clrscr();
printf("\n1.enter graph");
printf("\n2.adjency graph");
printf("\n3.prims algorithm");
printf("\n4.exit"); page|33
printf("\nenter your choice");
flushall();
scanf("%d",&choice);
switch(choice)
case 1:getgraph();
break;
case 2:printad();
break;
case 3:prims();
break;
case 4:exit(0);
getch();
OUTPUT:-
1.Enter graph
2.Adjacency graph
3.Prim's algorithm
4.Exit
1 2 3 4 5
2 4 286 5 3 286
3 6 5 286 286 5
1.Enter graph
4.Exit
2---->4 wt=3
2---->0 wt=0
2---->0 wt=0
2---->0 wt=0
CONCLUSION:-
Hence we have studied minimum cost spanning tree using prims algorithm.
EXPERIMENT NO:-06
THEORY:
In a binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-
based binary tree data structure which has the following properties
The left sub tree of a node contains only nodes with keys less than the node's key.
The right sub tree of a node contains only nodes with keys greater than the node's key.
The left and right sub tree each must also be a binary search tree.
There must be no duplicate nodes.
An optimal binary search tree is a binary search tree for which the nodes are arranged on levels such
that the tree cost is minimum.
A binary search tree of size 9 and depth 3, with root 8 and leaves 1, 4, 7 and 13
Page|36
Binary search tree
Type Tree
Time complexity
in big O notation
Algorithm : -
Wt(p,q,w,n)
For i to to n do
W[I,j]q[i]; //initialize
For m1 to n
do
do
{ Page|37
Ki+m;
W[I,k]w[I,k-1]+p[k]+q[k];
OBST(p,q,w,c,r)
For i=0 to n
do
C[I,i]0;
C[I,i+1]q[i]=q[i+1]+p[i+1];
R[I,i+1]I+1;
For m2 to n
do
For0 to n-m
do
Ji+m;
Kmin_value(c,r,I,j);
C[I,j]w[I,j]+c[I,k-1]+c[k,j];
r[I,j]k;
Min_value (c,r,i,j)
Minimuminfinity; Page|38
//finding the range of k
do
If(c[I,m-1]+c[m,j])<minimum
Minimumc[I,m-1]+c[m, j];
Km;
Build_tree (r,a,i,j)
Tnew(node);
Kr[I,j];
Tdataa[k];
If(j==i+1)
return;
Tleft=build_tree (r,a,I,k-1)
Tright=build_tree(r,a,k-i);
Page|39
PROGRAM:-
# include<stdio.h>
# include<conio.h>
# define SIZE 10
int p[SIZE];
int q[SIZE];
int a[SIZE];
int w[SIZE][SIZE];
int c[SIZE][SIZE];
int r[SIZE][SIZE];
int n;
void get_data()
int i;
clrscr();
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("\n p[%d]",i);
scanf("%d",&p[i]);
} Page|40
for(i=0;i<=n;i++)
printf("\n q[%d]",i);
scanf("%d",&q[i]);
int m,k;
int minimum=32000;
for(m=r[i][j-1];m<=r[i+1][j];i++)
if((c[i][m-1]+c[m][j])<minimum)
minimum=c[i][m-1]+c[m][j];
k=m;
return k;
void OBST()
int i,j,l,m;
for(i=0;i<n;i++)
w[i][i]=q[i];
r[i][i]=c[i][i]=0; Page|41
w[i][i+1]=q[i]+q[i+1]+p[i+1];
r[i][i+1]=i+1;
c[i][i+1]=q[i]+q[i+1]+p[i+1];
w[n][n]=q[n];
r[n][n]=c[n][n]=0;
for(m=2;m<=n;m++)
for(i=0;i<=n-m;i++)
j=i+m;
w[i][j]=w[i][j-1]+p[j]+q[j];
k=min_value(i,j);
c[i][j]=w[i][j]+c[i][k-1]+c[k][j];
r[i][j]=k;
void build_tree()
int i,j,k;
int queue[20],front=-1,rear=-1;
clrscr();
printf("the optimal binary search tree for the given nodes id..\n");
printf("\n...................................................");
queue[++rear]=0;
queue[++rear]=n;
while(front !=rear)
i=queue[++front];
j=queue[++front];
k=r[i][j];
printf("\n\t %d\t",k);
if(r[i][k-1]!=0)
printf("%d\t\t",r[i][k-1]);
queue[++rear]=k;
queue[++rear]=j;
else
printf("-\t");
printf("\n");
void main()
get_data();
OBST();
build_tree();
getch(); Page|43
}
OUTPUT:-
a[1]1
a[2]2
a[3]3
a[4]4
p[1]3
p[2]3
p[3]1
p[4]1
q[0]2
q[1]3
q[2]1
q[3]1
q[4]1
The optimal binary search tree for the given nodes is........................
2 1 3
1 - -
3 - 4
4 - -
EXPERIMENT NO:- 07
AIM:-
To solve traveling salesman problem using dynamic programming.
Theory:-
Dynamic programming:-
Dynamic programming is a technique for e ciently computing recurrences by storing partial
results and re-using them when needed.
We trade space for time, avoiding to repeat the computation of a subproblem.
Dynamic programming is best underestood by looking at a bunch of di erent examples.
The well-known travelling salesman problem is the following:
"A salesman is required to visit once and only once each of n different cities starting from a base
city, and returning to this city. What path minimizes the total distance travelledby the salesman?"
The problem has been treated by a number of different people using a variety of techniques; Dantzig,
Fulkerson, Johnson , where a combination of ingemtity and linear programming is used, and Miller, Tucker
and Zemlin , whose experiments using an all-integer program of Gomory did not produce results i cases with
ten cities although some success was achieved in eases of simply four cities. The purpose of this note is to
show that this problem can easily be formulated in dynamic programming terms, and resolved computa-
tionally for up to 17 cities. For larger numbers, the method presented below, combined with various simple
manipulations, may be used to obtain quick approximate solutions. Results of this nature were independently
obtained by
M. Held and R. M. Karp, who are in the process of publishing some extensions and computational results,
Dynamic Programming Formulation
Consider the problem as a multistage decision problem. With no loss in generality, since the
tour is a round trip, fix the origin at some city, say 0. Suppose that at a certain stage of an optimal tour
starting at 0 one has reached a city i and there remain k cities jl, j~, • • • , jk to be visited before returning to
0. Then it is clear that, the tour being optimal, the path from i through jl ,j2, • • • ,jk in some order and then
to 0 must be of minimum length; for, if not the entire tour could not be optimal, since its total length could
be reduced by choosing a shorter path from i through jl, j2, • • • , jk to 0. Therefore, let us define f(i; j~, j2, "
• • , jz) =- length of a path of minimum length from i to 0 which passes once and only once through each of
the re- (1) maining k unvisited cities jl, j2, • • • , fl • Thus, if we obtuin f(0; jl, j..,, • • • , j~), and a path which
has this length, the problem has been solved.
ALGORITHM:-
1. Declare a class dynamic with data members cost matrix, number of cities, distance array.
2. Declare a private member function to find out minimum of an array and public member functions
to getdata(), display(), swap(), fact(), permutations and solutions.
3. getdata()
o Read member of cities as n.
o For value of i from 1 to n by 1 repeat.
For values of j from 1 to n by 1 repeat.
Read c[i][j]
o For values of I varying from 0 to fact(n-1) by 1.
Let d[i]=0
4. swap(a,b)
o Let t=a.
o a=b
o b=t
5. min()
o Let m=d[0]
o For values of i to fact(n-1) by 1.
Check if (m>d[i]) if so
o Return m
6. sol()
o For values of I from 0 to n-2 by 1 repeat.
Let b[i]=i+2
o Call permutation function with b,o,n-2 as parameters.
7. fact()
o Let f=1.
o For values of I from 1 to m by 1 repeat.
f=f*i
o Return f
8. display()
o For values of I from 0 to fact(n-1) by 1 repeat
Print d[i]
o Print min(d)
o Using a while loop j<fact(n-1) print the path also.
9. perm(list[], k, m)
o Check if k=m if so
K1=1
For values of I from 0 to m by 1 repeat.
Path[i][i]=list[i]
d[i]= c[k1][list[i]]
k1=list[i]
d[i]=d[i]+c[k1][1]
let i=i+1
o else
for values of i from k to m by 1 repeat.
Call swap(list[k], list[i])
Call perm(list, k+1, m)
Call swap(list[k], list[i])
PROGRAM:-
//Travelling Salesman problem
#include <iostream.h>
#include <conio.h>
class dynamic
{
private:
int c[5][5],n,d[24],p[24][6],list[5],r;
public:
dynamic();
void getdata();
void display();
int fact(int num);
int min(int list[]);
void perm(int list[], int k, int m);
void sol();
};
dynamic::dynamic()
{
r=0;
}
void dynamic::getdata()
{
cout<<"Enter no. of cities:";
cin>>n;
cout<<endl;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
c[i][j]=0;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
if (i!=j)
{
if (c[i][j]==0)
{
cout<<"Enter cost from "<<i<<" to "<<j<<" :";
cin>>c[i][j];
c[j][i]=c[i][j];
}
}
}
}
for (i=0;i<n-1;i++)
list[i]=i+1;
}
void dynamic::sol()
{
perm(list,0,n-2);
for (int i=0;i<fact(n-1);i++)
{
p[i][0]=0;
p[i][n]=0;
}
for (i=0;i<fact(n-1);i++)
{
d[i]=0;
for (int j=0;j<n;j++)
{
d[i]=d[i]+c[p[i][j]][p[i][j+1]];
}
}
}
int dynamic::min(int list[])
{
int minimum=list[0];
for (int i=0;i<fact(n-1);i++)
{
if (list[i]<minimum)
minimum=list[i];
}
return minimum;
}
void dynamic::display()
{
int i,j;
cout<<endl<<"The cost Matrix:"<<endl;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
cout<<c[i][j]<<"\t";
cout<<endl;
}
cout<<endl<<"The Possible paths and their corresponding cost:"<<endl;
for (i=0;i<fact(n-1);i++)
{
for (j=0;j<n+1;j++)
cout<<p[i][j]<<"\t";
cout<<"--> "<<d[i]<<endl;
}
cout<<endl<<"The shortest path :"<<endl;
for (i=0;i<fact(n-1);i++)
{
if (d[i]==min(d))
break;
}
for (j=0;j<=n;j++)
{
cout<<p[i][j]<<" ";
}
cout<<endl<<"\nThe cost of this path is "<<d[i]<<endl;
}
void main()
{
clrscr();
dynamic ts;
ts.getdata();
ts.sol();
ts.display();
getch();
}
OUTPUT:-
Enter no. of cities:4
Enter cost from 0 to 1 :70
Enter cost from 0 to 2 :30
Enter cost from 0 to 3 :75
Enter cost from 1 to 2 :80
Enter cost from 1 to 3 :20
Enter cost from 2 to 3 :90
CONCLUSION :-
Thus , We studided travelling salesman problem using
Dynamic programming.
EXPERIMENT NO:-08
THEORY:-
2) Also every element on the same diagonal that goes from the upper right to
lower left has the same row + column value.Suppose two queens are placed at
positions (i,j) and (k,l),then by above they are on the same diagonal only if i-
j=k-l or i+j=k+l.
j-l=i-k
j-l=k-i
Thus the two queens lie on the same diagonal if and only if
|j-l|=|i-k|.
3) Above algorithm place (k,i)returns a Boolean value that is true if the kth
queen can be placed in column .It tests both whether i is distinct from all
previous values x [1],...,x[k-1]and whether there is no other queen on the same
diagonal .Its computing time is 0(k-1).The array x[]is a global. the algorithm
is NQueens (1,n).
Page|51
ALGORITHM:-
1. Algorithm NQueens(k,n)
2. Using backtracking ,this procedure prints all possible
placements of n queen
3. //an n*n chessboard so that they are nonattacking.
4. {
5. for i:=1 to n do
6. {
7.
8. if place(k,i) then
9. {
10. x[k]:=i;
11. if (k==n) then write (x[l:n]);
12. else NQueens(k+l,n);
13. }
14. }
15. }
PROGRAM:-
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<process.h>
int board[20];
int count;
void main()
clrscr();
scanf(“%d”,&n);
Queen(1,n);
getch();
void print_board(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++)
if(board[i]==j)
print(“\tQ”);
else
printf(“\t-“);
} ` Page|53
printf(“\nPress any key to continue..”);
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 1;
int column;
for(column=1;column<=n;column++)
if(place(row,column))
board[row]=column;
if(row==n)
print_board(n);
else
Queen(row+1,n); Page|54
}
OUTPUT:-
Solution 1:
1 2 3 4
1 - Q - -
2 - - - Q
3 Q - - -
4 - - Q -
CONCLUSION:-
EXPERIMENT NO:-09
Theory: -
A common subsequence of two strings is a subsequence that appears in both the strings.
A longest common subsequence is a common subsequence of maximal length.
Example:. Consider two strings of accordingly:
S1=AAACCGTGAGTTATTCGTTCTAGAA
S2=CACCCCTAAGGTACCTTTGGTTC
The longest common subsequence of the above string is
LCS=ACCTAGTACTTTG
A current research topic in bio-informatics. DNA are represented as strings of small alphabet,
Sigma={A,CG,T}.
DNA stands/ string can be change by mutation by insertion of character into the string.
\the longest common subsequence of two strings can be represent the common ancestry of two
strings.
ALGORITHM:-
LCS(X,Y)
Output: The tableL[i,j] the LCS for the sub peoblems x0x1…xi and y0y1…yj,
fori=-1 to n-1 do
L[i,-1]=0
L[-1,j]=0
fori=0 to n-1 do
if xi== yi then
L[i,j]=l[i-1,j-1]+1 page|56
else
Return L
PROGRAM:-
#include<conio.h>
#include<stdio.h>
#include<string.h>
void LCS(char X[20],char Y[20]);
void disp();
int L[20][20],n,m;
void main()
{
char X[20],Y[20];
printf("Enter the string X:\n");
scanf("%s",X);
n=strlen(X);
printf("Enter the string Y:\n");
scanf("%s",Y);
m=strlen(Y);
LCS(X,Y);
disp();
getch();
}
void disp()
{
int i,j;
for(i=0;i<=n-1;i++)
{
for(j=0;j<=m-1;j++)
printf("%d\t",L[i][j]);
printf("\n");
}
}
void LCS(char X[20],char Y[20])
{
int i,j;
for(i=-1;i<=n-1;i++)
L[i][-1]=0;
for(j=0;j<=m-1;j++)
L[-1][j]=0;
for(i=0;i<=n-1;i++)
for(j=0;j<=m-1;j++)
if(X[i]==Y[j])
L[i][j]=L[i-1][j-1]+1;
else
{
if(L[i-1][j]>L[i][j-1])
L[i][j]=L[i-1][j];
else
L[i][j]=L[i][j-1];
}
}
page|57
OUTPUT:-
Enter the string X:
ABCDBACDF
Enter the string Y:
CBAF
0 0 1 1
0 1 1 1
1 1 1 1
1 1 1 1
1 2 2 2
1 2 3 3
1 2 3 3
1 2 3 4
1 2 3 4
CONCLUSION-:
Thus we had succesfully implemented longest common subsequence algorithm.
EXPERIMENT NO:-10
THEORY:-
The 15-puzzle is an apparently simple puzzle for a single player, containing 15 numbered tiles and a
blank space on a 4x4 board. The puzzle is set up in a random configuration and the goal is to move
the tiles around until an ordered goal state is reached, having the tile numbers in order across and
down the board, with the blank in the bottom right-hand corner (see below). The only moves
available are to move a tile into a vertically or horizontally adjacent empty square. The state space
for this problem is quite large, containing approximately 1013 states, so exhaustive search is a poor
problem-solving strategy.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
1.Problem Representation
Formally represent the 24-puzzle problem.
Your assignment must contain the following:
1. List all relevant objects in the problem description and state the possible states of
the game, the initial state of the game, goal test conditions, and step cost / path
cost .
2. Represent the states in a well-known data structure, such as array, queue, stack,
linked list, or your choice of mathematical model and describe the representation
3. Represent the state space with mathematical formulas, operations (including the
successor function), and constraints and describe the representation .
4. Change the code appropriately from the 15-puzzle to the 24-puzzle and describe
the changes made.
2 Heuristic Functions
Implement the following heuristic functions.
1
h1 = the number of misplaced tiles
h2 = (Manhattan distance) the sum of the distances of the tiles from their goal
positions
1
3 Invented Heuristic Functions
Implement two new heuristic functions h3 and h4 .
Your assignment must contain the following for each heuristic:
You cannot use h1, h2, or the following heuristic function described in the text
book:
h5 = max{h1,h2}.
2
4 Informed Search Algorithms page|59
Implement the Greedy and A* search algorithms.
5 Repeated States
Implement detection of repeated states:
Your assignment must contain the following:
1. Formal description of how to detect and avoid repeated states .
1
2. Pseudocode showing how you detect and avoid repeated states, including
comments and a description.
6 Evaluate
Evaluate the four heuristic functions with Greedy and A* search.
Note: You can use the supplied code for generating random puzzle states to collect
test results for each depth. Then, run the supplied code (in Node.java) or write
and run your own code to calculate EBFs for each depth. For each test run, you
need to obtain the total number of nodes generated and the depth (solution
length) to obtain its effective branching factor.
4
- Program documentation
Source code is well documented, uses meaningful variable names and correct
indentation.
0.5
- Report
Report is well presen
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 0
In all cases, describe how to compile/interpret and run your program (include name and version of
compiler/interpreter).
Once again, where possible, include your student number (if working individually) or both student
numbers with a separator (if working in a pair) at the beginning of submitted filenames. An
exception - in Java, use search.jar, as described below. Also make sure to include your name and
student number(s) in your document and in any modified code files.
If using the supplied Java code to implement your own FifteenSearchApp.solveH1G(),
FifteenSearchApp.solveH1A() etc we should be able to test and evaluate your code.
Otherwise, you need to provide basic test and evaluation code foryour program and document this.
page|60
ALGORITHM :-
Solve =(startGrid)→
Frontier=new priority queue
Frontier enqueue (new solver state(startgrid,[]))
While not frontier .empty()
Curstate= frontier.dequeue()
If curstate.solved
return curstate.steps
candidate moves=grid.validmoves()
for move in candidatemoves
nextsteps=curstate.steps.concat([move])
nextstate=new solver state
(nextGrid ,nextstpes)
Frontier.enqueue(nextstate)
PROGRAM:-
void moveLeft(void);
void moveUp(void);
void moveDown(void);
void ownsetup (void);
void randomizer(void);
int checkForFinish(void);
main(void)
{
int RorY;
printf("Hello, and welcome to Hunter's 15-puzzle!\n");
printf("To play a Randomly Generated Puzzle Press r\n");
printf("To set up your own puzzle press y\n");
RorY = getchar();
if(RorY == 'r')
randomizer();
if(RorY == 'o')
ownsetup();
displayTable();
EXPERIMENT NO:-11
THEORY:-
Let G be graph and m be a given positive integer. With m colors we have to check whether the nodes
of G can be colored in such a way that no two adjacent nodes have the same color.
The m color ability optimization problems asks for the smallest integer m for which the graph G can
be colored. This integer is referred as chromatic number of the graph.
The graph nodes can be colored with three colors 1,2 and 3 in the above figure. The color of each
node is indicated by the number 1,2 or 3 next to it. Since the graph has 3 colors, its chromatic number is 3.
graph coloring is a special case of graph labeling; it is an assignment of labels traditionally called
"colors" to elements of a graph subject to certain constraints. In its simplest form, it is a way of coloring the
vertices of a graph such that no two adjacent vertices share the same color; this is called a vertex coloring.
Similarly, an edge coloring assigns a color to each edge so that no two adjacent edges share the same color,
and a face coloring of a planar graph assigns a color to each face or region so that no two faces that share a
boundary have the same color.
ALGORITHM:-
1. Algorithm m coloring(k)
2. //This algorithm was formed using the recursive backtracking schema.The graph is
3. //represented by it’s boolean adjacency matrix G[1:n,1:n].All assignments of
4. //1,2……m to the vertices of the graph such that adjacent are assigned distinct
5. // integers are printed, k is the index of the next vertex to color.
6. {
7. Repeat
8. { //Generate all legal assignments for x[k].
9. NextValue(k); //Asign to x[k] a legal color.
10. If(x[k]=0) then return; //No new color possible
11. If(k=n) then // At most m colors have been used to color the n vertices. page|65
12. Write(x[1:n]);
13. Else mColoring(k+1)’
14. } until(false);
15. }
1. Algorithm NextValue(k)
2. //x[1],…..x[k-1] have been assigned integer values in the
3. //range[1,m]such that adjacent vertices have distinct
4. Integers. A value for x[k] is determined in the range
5. //[0,m].x[k] is assigned the next highest membered color
6. //while maintaining distinctness from the adjacent vertices
7. //of vertex k. If no such color exist, then x[k] is 0.
8. {
9. Repeat
10. {
11. X[k]:=(x[k]+1mod(m+1)); //next highest color
12. If (x[k]=0)then return; //all colors have been used.
13. For J:=1 to n do
14. { //check if this color distinct from adjacent colors.
15. If((G[k,j]!=0)and(x[k]=x[j]) )
16. //if(k,j) is and edge and if adjacent vertices
17. //have the same color
18. Then break;
19. }
20. If(j=n+1)then return; //new color found
21. } until(false); //otherwise try to fing another color
22. }
PROGRAM:-
#include<stdio.h>
#include<conio.h>
int m,n,x[10],graph[10][10];
void mcolor(int k)
{
int i;
while(1)
{
callnextvalue(k);
if(x[k]==0)break;
if(k==n)
{
for(i=1;i<=n;i++) page|66
printf("%d\n\t",x[i]);
}
else
mcolor(k+1);
}
}
int callnextvalue(int k)
{
int j;
while(1)
{
x[k]=(x[k]+1)%(m+1);
if(x[k]==0) return 0;
for(j=1;j<=n;j++)
if(graph[k][j]&&x[k]==x[j])
break;
if(j==n+1) return 0;
}
}
void main()
{
int i,e,a,b;
clrscr();
printf("ENTER THE VERTICES\n");
scanf("%d",&n);
printf("ENTER NO.OF EDGES:\n");
scanf("%d",&e);
for(i=1;i<=e;i++)
{
printf("ENTER EDGE:\n");
scanf("%d%d",a,b);
graph[a][b]=1;
graph[b][a]=1;
}
for(i=1;i<=n;i++)
x[i]=0;
printf("ENTER NO.OF COLORS:\n");
scanf("%d",&m);
printf("FOLLOWING ARE NO. OF WAYS IN WHICH NODES CAN BE COLORED\n");
mcolor(1);
getch();
}
page|67
OUTPUT:-
12313
12323
13212
13232
21313
21323
23121
23131
31212
31232
32121
32131
CONCLUSION:-
Thus we have concluded, how to implement the Graph Coloring Problem.
EXPERIMENT NO:-12
ALGORITHM:-
void matmul(int *A, int *B, int *R, int n)
{
if(n == 1) then
{
(*R) += (*A) * (*B);
}
else
{
matmul(A, B, R, n/4);
matmul(A, B+(n/4), R+(n/4), n/4);
matmul(A+2*(n/4), B, R+2*(n/4), n/4);
matmul(A+2*(n/4), B+(n/4), R+3*(n/4), n/4);
matmul(A+(n/4), B+2*(n/4), R, n/4); page|70
matmul(A+(n/4), B+3*(n/4), R+(n/4), n/4);
matmul(A+3*(n/4), B+2*(n/4), R+2*(n/4), n/4);
matmul(A+3*(n/4), B+3*(n/4), R+3*(n/4), n/4);
}
PROGRAM:-
#include<stdio.h>
int main()
{
int a[2][2],b[2][2],c[2][2],i,j;
int m1,m2,m3,m4,m5,m6,m7;
printf("Enter the 4 elements of first matrix: ");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("Enter the 4 elements of second matrix: ");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
printf("\nThe first matrix is\n");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
printf("\n");
for(j=0;j<2;j++)
page|71
printf("%d\t",b[i][j]);
m2= (a[1][0]+a[1][1])*b[0][0];
m3= a[0][0]*(b[0][1]-b[1][1]);
m4= a[1][1]*(b[1][0]-b[0][0]);
m5= (a[0][0]+a[0][1])*b[1][1];
m6= (a[1][0]-a[0][0])*(b[0][0]+b[0][1]);
m7= (a[0][1]-a[1][1])*(b[1][0]+b[1][1]);
c[0][0]=m1+m4-m5+m7;
c[0][1]=m3+m5;
c[1][0]=m2+m4;
c[1][1]=m1-m2+m3+m6;
for(i=0;i<2;i++)
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",c[i][j]);
return 0;
page|72
OUTPUT:-
Enter the 4 elements of first matrix: 1
2
3
4
Enter the 4 elements of second matrix: 5
6
7
8
1 2
3 4
The second matrix is
5 6
7 8
After multiplication using
19 22
43 50
THEORY: The average and best case running time of the Rabin-Karp algorithm is O(n+m), but its worst-
case time is O(nm). Worst case of Rabin-Karp algorithm occurs when all characters of pattern and text are
same as the hash values of all the substrings of txt[] match with hash value of pat[]. For example pat[] =
“AAA” and txt[] = “AAAAAAA”.
Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text,
and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm
needs to calculate hash values for following strings.
1) Pattern itself.
2) All the substrings of text of length m.
Since we need to efficiently calculate hash values for all the substrings of size m of text, we must have a
hash function which has following property.
Hash at the next shift must be efficiently computable from the current hash value and next character in text
or we can say hash(txt[s+1 .. s+m]) must be efficiently computable from hash(txt[s .. s+m-
1])and txt[s+m] i.e., hash(txt[s+1 .. s+m])= rehash(txt[s+m], hash(txt[s .. s+m-1]) and rehash must be O(1)
operation.
The hash function suggested by Rabin and Karp calculates an integer value. The integer value for a string is
numeric value of a string. For example, if all possible characters are from 1 to 10, the numeric value of
“122” will be 122. The number of possible characters is higher than 10 (256 in general) and pattern length
can be large. So the numeric values cannot be practically stored as an integer. Therefore, the numeric value
is calculated using modular arithmetic to make sure that the hash values can be stored in an integer variable
(can fit in memory words). To do rehashing, we need to take off the most significant digit and add the new
least significant digit for in hash value. Rehashing is done using the following formula.
hash( txt[s+1 .. s+m] ) = ( d ( hash( txt[s .. s+m-1]) – txt[s]*h ) + txt[s + m] ) mod q
hash( txt[s .. s+m-1] ): Hash value at shift s.
hash( txt[s+1 .. s+m] ): Hash value at next shift (or shift s+1)
d: Number of characters in the alphabet
q: A prime number
h: d^(m-1)
if ( p == t )
{
EXPT. NO. 14
THEORY:
ALGORITHM:
THEORY:
Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of
elements and the number of possible key values are approximately the same.
It requires O(n + Range) time where n is number of elements in input array and ‘Range’ is number of
possible values in array.
Working of Algorithm :
1. Find minimum and maximum values in array. Let the minimum and maximum values be ‘min’ and
‘max’ respectively. Also find range as ‘max-min-1’.
2. Set up an array of initially empty “pigeonholes” the same size as of the range.
3. Visit each element of the array and then put each element in its pigeonhole. An element arr[i] is put in
hole at index arr[i] – min.
4. Start the loop all over the pigeonhole array in order and put the elements from non- empty holes back
into the original array.
def pigeonhole_sort(a):
mi = min(a)
size = max(a) - mi + 1
holes = [0] * size
for x in a:
holes[x - mi] += 1
i=0
for count in xrange(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + mi
i += 1
#include <stdio.h> holes[*current-mi] += 1;
}
#define MAX 7 for (count = 0, current = &a[0]; count < size
; count++)
void pigeonhole_sort(int, int, int *); {
void main() while (holes[count]--> 0)
{ {
int a[MAX], i, min, max; *current++ = count + mi;
printf("enter the values into the matrix :"); }
for (i = 0; i < MAX; i++) }
{ }
scanf("%d", &a[i]);
}
min = a[0];
max = a[0];
for (i = 1; i < MAX; i++)
{
if (a[i] < min)
{
min = a[i];
}
if (a[i] > max)
{
max = a[i];
}
}
pigeonhole_sort(min, max, a);
printf("Sorted order is :\n");
for (i = 0; i < MAX; i++)
{
printf("%d", a[i]);
}
}
int maxOverlaps = 0;
FOR i = 0 TO n-1
int numberOfOverLaps = 0;
FOR j = i+1 TO n-1
IF train[i] OVERLAPS WITH train[j] THEN
numberOfOverLaps++;
IF numberOfOverLaps > maxOverlaps THEN
maxOverlaps = numberOfOverLaps;
RETURN maxOverlaps;
Time Complexity: O(nLogn), assuming that a O(nLogn) sorting algorithm for sorting arr[] and dep[].
// Program to find minimum number of platforms
// required on a railway station
#include<iostream>
#include<algorithm>
using namespace std;
return result;
}
// Driver program to test methods of graph class
int main()
{
int arr[] = {900, 940, 950, 1100, 1500, 1800};
int dep[] = {910, 1200, 1120, 1130, 1900, 2000};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Minimum Number of Platforms Required = "
<< findPlatform(arr, dep, n);
return 0;
}