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

Analysis of Search and Sorting Algorithms

practicals of daa

Uploaded by

prespective
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views51 pages

Analysis of Search and Sorting Algorithms

practicals of daa

Uploaded by

prespective
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

1. Study and analyse linear search and binary search algorithms.


2. Study and analyse the average case, worst case and best case for sorting
[Link] discuss various factors on which running time of
algorithm depends :
1) Insertion sort.
2) Merge sort.
3) Quick sort.
3. Study and analyse Prim’s and Kruskal’s algorithm to find minimum
spanning tree in a weighted graph.
4. Study and analyse Counting sort.
5. Study and analyse solution to matrix chain multiplication using dynamic
programming technique.
6. Study and analyse Straassen’s algorithm to multiply two square
matrices.
7. Study and analyse Knapsack problem.
8. Study and analyse Dijkstra’s algorithm for single source shortest path in
a weighted graph.
9. Study and analyse Floyd Warshall’s algorithm.
10. Study and analyse N-Queens problem using backtracking.
11. Study and analyse Huffman coding.
12. Study and analyse Radix sort.
PROGRAM 1

Study and analyse linear search and binary search

#include<stdio.h>
#include<conio.h>
void lin_search(int b[50],int n);
int bin_search(int b[50],int low,int high);
int item,cost = 0;

void main( )
{
int a[50],i,n,loc;
clrscr( );

printf("Enter the size of array :");


scanf("%d",&n);

printf("\nArray elements(ascending order)\n");


for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("\nEnter the element to be searched :");


scanf("%d",&item);

printf("\nResults of linear search\n");


lin_search(a,n);

printf("\nResults of linear search\n");


loc = bin_search(a,0,n);

if(loc==0)
printf("Unsuccessful serach.%d not found.\n",item);
else
{
printf("Successful search\n");
printf("%d found at position %d.\n",item,loc);
}
printf("The cost of running binary search is %d\n",cost);
getch( );
}
void lin_search(int b[50],int n)
{
int i,flag = 1,cost = 0 ;
for(i=0;i<n;i++)
{
cost++;
if(b[i]==item)
{
printf("Successful search\n");
printf("%d found at position %d.\n",item,i+1);
flag = 0;
break;
}
}
if(flag)
printf("Unsuccessful serach.%d not found.\n",item);
printf("The cost of running linear search is %d\n",cost);
}

int bin_search(int b[50],int low,int high)


{
int mid,i;
if(low<=high)
{
cost++;
mid = (low+high)/2;
if(item<b[mid])
{
high = mid - 1;
bin_search(b,low,high);
}
else if(item>b[mid])
{
low = mid + 1;
bin_search(b,low,high);
}
else
return(mid+1);
}
else
return(0);
}
OUTPUT
Enter the size of array :8

Array elements(ascending order)


1
3
5
7
9
12
45
67

Enter the element to be searched :12

Results of linear search


Successful search
12 found at position 6.
The cost of running linear serach is 6

Results of linear search


Successful search
12 found at position 6.
The cost of running binary serach is 3
PROGRAM 2

Study and analyse the average case, worst case and best case for sorting
[Link] discuss various factors on which running time of
algorithm depends :
1) Insertion sort.
2) Merge sort.
3) Quick sort.

#include<stdio.h>
#include<conio.h>
void insertion_sort(int a[],int n);
void merge_sort(int a[],int p,int r);
void merge(int a[],int p,int q,int r);
int partition(int a[],int p,int r);
void quick_sort(int a[],int p,int r);
int cost = 0;

void main( )
{
int n,a[50],b[50],c[50],i,j;
clrscr( );
printf("Enter the number of elements to be sorted :");
scanf("%d",&n);
printf("\nEnter the elements :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{
b[i] = a[i];
c[i] = a[i];
}

printf("\nResult of insertion sort\n");


insertion_sort(a,n);

printf("\n\nResult of merge sort\n");


merge_sort(b,1,n);
for(i=1;i<=n;i++)
printf("%d ",b[i]);
printf("\nThe cost of running merge sort is %d",cost);
cost = 0;
printf("\n\nResult of quick sort\n");
quick_sort(c,1,n);

for(i=1;i<=n;i++)
printf("%d ",c[i]);
printf("\nThe cost of running quick sort is %d",cost);
getch();

void insertion_sort(int a[],int n)


{
int i,j,key,cost=0;

for(j=2;j<=n;j++)
{
cost++;
key = a[j];
i = j-1;
while(i>0 && a[i]>key)
{
cost++;
a[i+1] = a[i];
i = i-1;
}
a[i+1] = key;
}
for(i=1;i<=n;i++)
printf("%d ",a[i]);
printf("\nThe cost of running insertion sort is %d",cost);
}

void merge_sort(int a[],int p,int r)


{
int q,i;
if(p<r)
{
cost++;
q = (p+r)/2;
merge_sort(a,p,q);
merge_sort(a,q+1,r);
merge(a,p,q,r);
}
}

void merge(int a[],int p,int q,int r)


{
int n1,n2,L[20],R[20],i,j,k,infinity=10000;
n1 = q-p+1;
n2 = r-q;
for(i=1;i<=n1;i++)
L[i] = a[p+i-1];
for(j=1;j<=n2;j++)
R[j] = a[q+j];
L[n1+1] = infinity;
R[n2+1] = infinity;
i = 1;
j = 1;
for(k=p;k<=r;k++)
{
cost++;
if(L[i]<=R[j])
{
a[k] = L[i];
i = i+1;
}
else
{
a[k] = R[j];
j = j+1;
}
}
}

void quick_sort(int a[],int p,int r)


{
int q,i;
if(p<r)
{
cost++;
q = partition(a,p,r);
quick_sort(a,p,q-1);
quick_sort(a,q+1,r);
}
}

int partition(int a[ ],int p,int r)


{
int x,i,j,temp;
x = a[r];
i = p-1;
for(j=p;j<r;j++)
{
cost++;
if(a[j]<=x)
{
i = i+1;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[i+1];
a[i+1] = a[r];
a[r] =temp;
return(i+1);
}

OUTPUT

Enter the number of elements to be sorted :10

Enter the elements :


6 5 2 1 4 7 9 3 5 4

Result of insertion sort


1234455679
The cost of running insertion sort is 30

Result of merge sort


1234455679
The cost of running merge sort is 43

Result of quick sort


1234455679
The cost of running quick sort is 25
PROGRAM 3

Study and analyse Prim’s and Kruskal’s algorithm to find minimum


spanning tree in a weighted graph

PRIM’S ALGORITHM

#include<stdio.h>
#include<conio.h>
#define size 20

typedef enum
{
true = 1,
false = 0
}boolean;

void disp(int a[size][size],int n)


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

int min(int a[size],int n,int *j)


{
int i,m;
m = a[0];
*j = -1;

for(i=0;i<n;i++)
if(a[i]&&(!m||m>a[i]))
{
m = a[i];
*j = i;
}
return m;
}
void main( )
{

int a[size][size],c[size],i,j,k,l,m,n,nodused,cost,minm;
boolean f1,isof;
clrscr( );

printf("To compute the spanning tree from the adjacency matrix\n");


printf("How many nodes :");
scanf("%d",&n);

printf("Enter the adjacency matrix :");


for(i=0;i<n;i++)
{
c[i] = 0;
for(j=0;j<n;j++)
{
scanf("%d",&k);
a[i][j] = k;
}
}

printf("\nThe entered adjacency matrix :\n");


disp(a,n);
printf("\n");

for(i=0;i<n;i++)
{
a[i][i] = 0;
for(j=i+1;j<n;j++)
{
if(a[i][j]==0)
a[i][j] = a[j][i];
else
if(a[j][i]<a[i][j]&&a[j][i]!=0)
a[i][j] = a[j][i];
a[j][i] = a[i][j];
}
}
printf("The nodes to be connected in spanning tree are :\n");
f1 = false;
c[0]=1;
cost = 0;
nodused = 1;

while(!f1)
{
minm = 0;
isof = false;
for(i=0;i<n;i++)
if(c[i]!=0)
{
m = min(a[i],n,&j);
if(j>-1)
if(c[j]!=0)
{
a[i][j] = 0;
a[j][i] = 0;
isof = true;
}
else
if(minm==0||(m<minm&&m!=0))
{
minm = m;
k = j;
l = i;
}
}

if(minm!=0)
{
printf("(%d,%d);",l+1,k+1);
cost = cost +a[l][k];
a[l][k] = 0;
a[k][l] = 0;
c[k] = 1;
nodused = nodused+1;
}
else if(!isof)
{
printf("Isolated nodes found!\n");
f1 = true;
}
if(nodused>=n)
f1 = true;
}

printf("\n");
printf("The cost of tree is :%d",cost);
getch( );
}

OUTPUT

To compute the spanning tree from the adjacency matrix


How many nodes :7

Enter the adjacency matrix :


0 2 4 1 0 0 0
2 0 0 3 10 0 0
4 0 0 2 0 5 0
1 3 2 0 7 8 4
0 10 0 7 0 0 6
0 0 5 8 0 0 1
0 0 0 4 6 1 0

The nodes to be connected in spanning tree are :


(1,4);(1,2);(4,3);(4,7);(7,6);(7,5);
The cost of tree is :16
KRUSKAL’ S ALGORITHM

#include<stdio.h>
#include<malloc.h>
#include<conio.h>
#define max(a,b)((a)>(b)?(a):(b))

struct ll_node{
struct ll_node *next;
int src,dest;
int weight;
};

int *parent;
char err_iso[ ] = "some nodes in the tree are isolated\n";
void error(char *msg)
{
puts(msg);
exit(1);
}
void put_sorted(struct ll_node *phead,struct ll_node *node)
{
struct ll_node *current,*prev;
prev = phead;
current = phead->next;

while(current&&current->weight<node->weight)
{
prev = current;
current = current->next;
}
node->next = current;
prev->next = node;
}

int input(struct ll_node *phead)


{
char c;
int readover = 0;
int i,j,n = 0,weight;
struct ll_node *node;
char inps[80];
printf("Input as adjacency matrix or adjacency list?(A/E)");
scanf("%c",&c);
fflush(stdin);
do
{
switch(c)
{
case 'A':
case 'a':readover = 1;
printf("no of nodes :");
scanf("%d",&n);
printf("Input as adjacency matrix:\n");
for(i=0;i<n;i++)
{
printf("\nRow %d:",i+1);
for(j=0;j<n;j++)
{
scanf("%d",&weight);
if(weight)
{
node =(struct ll_node*)malloc(sizeof(struct ll_node));
node->src = i;
node->dest = j;
node->weight = weight;
put_sorted(phead,node);
}
}
}
break;
case 'E':
case 'e':readover = 1;
printf("Input the edges as <src> <dest> <weight>.\n");
printf("(Input non-numerals to terminate)\n");
gets(inps);

while(sscanf(inps,"%d%d%d",&i,&j,&weight)==3)
{

node = (struct ll_node*)malloc(sizeof (struct ll_node));


node->src = i-1;
node->dest = j-1;
node->weight = weight;
n = max(n,i);
n = max(n,j);
put_sorted(phead,node);
fflush(stdin);
gets(inps);
}
break;
default:readover = 0;
scanf("%c",&c);
fflush(stdin);
}
}while(!readover);
return n;
}

int root(int *parent,int node)


{
while(parent[node]!=node)
node = parent[node];
return node;
}

int min_span(struct ll_node *phead,int n)


{
struct ll_node *first,*current,*temp;
int *parent;
int i,root_src,root_dest,nedges;

parent = (int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
parent[i] = i;

current = phead->next;
while(current&&current->src==current->dest)
current = current->next;
if(!current)
error(err_iso);
first = current;
parent[first->dest] = first->src;
nedges = 1;

current = first->next;
first->next = NULL;
while(current||nedges<n-1)
{
temp = current->next;
root_src = root(parent,current->src);
root_dest = root(parent,current->dest);

if(root_dest!=root_src)
{
current->next = first;
first = current;
parent[root_dest] = root_src;
nedges++;
}
else
free(current);
current = temp;
}
phead->next = first;
return nedges;
}

void main( )
{
int n;
struct ll_node head;
struct ll_node *current;
clrscr();

[Link] = NULL;
n = input(&head);

if(min_span(&head,n)!=n-1)
error(err_iso);
current = [Link];
printf("The minimum spanning tree has the following edges:\n");
while(current)
{
printf("%d-%d\n",current->src+1,current->dest+1);
current = current->next;
}
getch( );
}
OUTPUT

Input as adjacency matrix or adjacency list?(A/E)E


Input the edges as <src> <dest> <weight>.
(Input non-numerals to terminate)
1 2 2
1 3 4
1 4 1
2 4 3
2 5 10
3 4 2
3 6 5
4 6 8
4 7 4
4 5 7
5 7 6
6 7 1
E

The minimum spanning tree has the following edges:


5-7
4-7
1-2
3-4
1-4
6-7
PROGRAM 4
Study and analyse Counting sort

#include<stdio.h>
int * counting_sort(int A[ ],int B[ ],int k,int n)
{
int i,j,C[20];
for(i=0;i<=k;i++)
C[i] = 0;
for(j=1;j<=n;j++)
C[A[j]] = C[A[j]]+1;
for(i=1;i<=k;i++)
C[i] = C[i]+C[i-1];
for(j=n;j>=1;j--)
{
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]]-1;
}
return B;
}
void main( )
{
int n,i,A[20],k = 0,j,B[20],*C;
printf("\nEnter the number of elements in the array :");
scanf("%d",&n);
printf("\nEnter the elements of array :\n");
for(i=1;i<=n;i++)
scanf("%d",&A[i]);
for(i=1;i<=n;i++)
if(A[i]>k)
k = A[i];
C = counting_sort(A,B,k,n);
for(i=1;i<=n;i++)
{ C++;
printf("%d ",*C);
}
}
OUTPUT

Enter the number of elements in the array :5


Enter the elements of array :5 6 7 2 1
Elements in sorted array are :1 2 5 6 7
PROGRAM 5

Study and analyse solution to matrix chain multiplication using


dynamic programming technique

#include<stdio.h>
#include<conio.h>
void matrix_chain_order( );
void print_optimal_parens(int i,int j);

unsigned long int m[10][10];


int p[10],s[10][10],n;

void main( )
{
int i,j;
clrscr( );
printf("\nEnter the no of matrices to be multiplied :");
scanf("%d",&n);
printf("\nEnter the dimensions of matrices :\n");
for(i=0;i<=n;i++)
scanf("%d",&p[i]);
matrix_chain_order( );
printf(“Optimal parenthesization for these matrices is :”);
print_optimal_parens(1,n);
getch( );
}

void matrix_chain_order( )
{
int i,j,l,q,k;
for(i=1;i<=n;i++)
m[i][i] = 0;

for(l=2;l<=n;l++)
for(i=1;i<=n-l+1;i++)
{
j = i+l-1;
m[i][j] = 50000;

for(k=i;k<=j-1;k++)
{
q = m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(q<m[i][j])
{
m[i][j] = q;
s[i][j] = k;
}
}
}
}

void print_optimal_parens(int i,int j)


{
if(i==j)
printf("A%d ",i);
else
{
printf("(");
print_optimal_parens(i,s[i][j]);
print_optimal_parens(s[i][j]+1,j);
printf(")");
}
}

OUTPUT

Enter the no of matrices to be multiplied :6

Enter the dimensions of matrices :


30 35 15 5 10 20 25

Optimal parenthesization for these matrices is :


((A1 (A2 A3 ))((A4 A5 )A6 ))
Matrix chain multiplication using recursive procedure

#include<stdio.h>
#include<conio.h>
#include<limits.h>
#define infinity INT_MAX
int recursive_matrix_chain(int i,int j);
void print_optimal_parens(int i,int j);

unsigned long int m[10][10];


int p[10],s[10][10],n;
void main( )
{
int i,j;
clrscr( );
printf("\nEnter the no of matrices to be multiplied :");
scanf("%d",&n);
printf("\nEnter the dimensions of matrices :\n");
for(i=0;i<=n;i++)
scanf("%d",&p[i]);
recursive_matrix_chain(1,n);
printf(“Optimal parenthesization for these matrices is :”);
print_optimal_parens(1,n);
getch( );
}

int recursive_matrix_chain(int i,int j)


{
int q,k;
if(i==j)
return 0;
m[i][j] = infinity;
for(k=i;k<=j-1;k++)
{
q =recursive_matrix_chain(i,k)+recursive_matrix_chain(k+1,j)+p[i-
1]*p[k]*p[j];
if(q<m[i][j])
{
m[i][j] = q;
s[i][j] = k;
}
}
return(m[i][j]);
}

void print_optimal_parens(int i,int j)


{
if(i==j)
printf("A%d ",i);
else
{
printf("(");
print_optimal_parens(i,s[i][j]);
print_optimal_parens(s[i][j]+1,j);
printf(")");
}
}

OUTPUT

Enter the no of matrices to be multiplied :5

Enter the dimensions of matrices :


20 50 25 15 30 10

Optimal parenthesization for these matrices is :


(A1 (A2 (A3 (A4 A5 ))))
Matrix Chain Multiplication Using Memoization

#include<stdio.h>
#include<conio.h>
#include<limits.h>
#define infinity INT_MAX
void memoized_matrix_chain( );
int look_up_chain(int i,int j);
void print_optimal_parens(int i,int j);

unsigned long int m[10][10];


int p[10],s[10][10],n;
void main( )
{
int i,j;
clrscr( );
printf("\nEnter the no of matrices to be multiplied :");
scanf("%d",&n);
printf("\nEnter the dimensions of matrices :\n");
for(i=0;i<=n;i++)
scanf("%d",&p[i]);
memoized_matrix_chain(1,n);
printf(“Optimal parenthesization for these matrices is :”);
print_optimal_parens(1,n);
getch( );
}

void memoized_matrix_chain( )
{
int i,j;
for(i=1;i<=n;i++)
for(j=i;j<=n;j++)
m[i][j] = infinity;
look_up_chain(1,n);
}

int look_up_chain(int i,int j)


{
int q,k;
if(m[i][j] <infinity)
return(m[i][j]);

if(i==j)
m[i][j] = 0;
else
{
for(k=i;k<=j-1;k++)
{
q = look_up_chain(i,k)+look_up_chain(k+1,j)+p[i-1]*p[k]*p[j];
if(q<m[i][j])
{
m[i][j] = q;
s[i][j] = k;
}
}
}
return(m[i][j]);
}

void print_optimal_parens(int i,int j)


{
if(i==j)
printf("A%d ",i);
else
{
printf("(");
print_optimal_parens(i,s[i][j]);
print_optimal_parens(s[i][j]+1,j);
printf(")");
}
}

OUTPUT
Enter the no of matrices to be multiplied :7

Enter the dimensions of matrices :


15 10 5 20 15 25 30 10

Optimal parenthesization for these matrices is :


((A1 A2 )((((A3 A4 )A5 )A6 )A7 ))
PROGRAM 6

Strassen Algorithm For Matrix Multiplication

#include<stdio.h>
#include<conio.h>

void main( )
{
int a[2][2],b[2][2],p[7],c[2][2],i,j,n;
clrscr( );
printf("\nEnter elements of matrix a:\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);

printf("\nEnter elements of matrix b:\n");


for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);

p[0] = a[0][0]*(b[0][1]-b[1][1]);
p[1] = (a[0][0]+a[0][1])*b[1][1]);
p[2] = (a[1][0]*a[1][1])*b[0][0]);
p[3] = a[1][1]*(b[1][0]-b[0][0]);
p[4] = (a[0][0]+a[1][1])*(b[0][0]+b[1][1]);
p[5] = (a[0][1]-a[1][1])*(b[1][0]+b[1][1]);
p[6] = (a[0][0]-a[1][0])*(b[0][0]+b[0][1]);

c[0][0] = p[4]+p[3]-p[1]+p[5];
c[0][1] = p[0]+p[1];
c[1][0] = p[2]+p[3];
c[1][1] = p[4]+p[0]-p[2]-p[6];

printf("\nThe product of matrices is :\n");


for(i=0;i<n;i++)
{ printf("\n");
for(j=0;j<n;j++)
printf("%4d",c[i][j]);
}
getch( );
}
OUTPUT
Enter elements of matrix a:
5 6
4 2

Enter elements of matrix b:


7 3
1 4

The product of matrices is :

41 39
44 6
PROGRAM 7

Study and analyse Knapsack problem

#include<conio.h>
float x[10];
void knapsack( );
int m,n,i,j;
float p[10],w[10],p_w[10],temp,sum=0.0,sp=0.0;

void main( )
{
clrscr( );
printf("\nEnter the number of items :");
scanf("%d",&n);
printf("\nEnter the maximum weight that can be carried by knapsack :");
scanf("%d",&m);
printf("Enter the weight of each item item :\n");
for(i=0;i<n;i++)
scanf("%f",&w[i]);
printf("\nEnter the priority of each item :\n");
for(i=0;i<n;i++)
scanf("%f",&p[i]);

for(i=0;i<n;i++)
p_w[i]=p[i]/w[i];

for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(p_w[i]<p_w[j])
{
temp = p_w[i];
p_w[i]= p_w[j];
p_w[j]=temp;

temp = w[i];
w[i]= w[j];
w[j]=temp;

temp = p[i];
p[i]= p[j];
p[j]=temp;
}

knapsack( );
printf("\nThe resulting weight,priorities,parts are :\n");
printf("Weight\t\tPriority\t\tPart\n");
for(i=0;i<n;i++)
printf("%f\t%f\t%f\n",w[i],p[i],x[i]);
printf("\nThe total weight carried by knapsack :");
for(i=0;i<n;i++)
sum=sum+x[i]*w[i];
printf("%f\n",sum);

printf("\nThe part-priority summation is :");


for(i=0;i<n;i++)
sp=sp+x[i]*p[i];

printf("%f\n",sp);
getch( );

void knapsack( )
{
int i;
float u;
for(i=0;i<n;i++)
x[i]=0.0;
u=m;
for(i=0;i<n;i++)
if(w[i]>u)
break;
else
{
x[i]=1;
u=u-w[i];
}
if(i<n)
x[i]=u/w[i];
}
OUTPUT

Enter the number of items :3

Enter the maximum weight that can be carried by knapsack :20

Enter the weight of each item item :


18 15 10

Enter the priority of each item :


25 24 15

The resulting weight,priorities,parts are :

Weight Priority Part


15.000000 24.000000 1.000000
10.000000 15.000000 0.500000
18.000000 25.000000 0.000000

The total weight carried by knapsack :20.000000

The part-priority summation is :31.500000


PROGRAM 10

Study and analyse N-queens problem using backtracking


#include<stdio.h>
#include<conio.h>
int x[20];
void main( )
{
int n;
clrscr( );

printf("Enter the number of queens to be placed :");


scanf("%d",&n);

printf("The possible combinations of placing %d queens in a %dX%d


chessboard are :\n\n",n,n,n);

Nqueen(1,n);
getch( );
}

Nqueen(int k,int n)
{
int i,j;
for(i = 1;i<=n;i++)
{
if(place(k,i))
{
x[k] = i;
if(k==n)
{
for(i=1;i<=n;i++)
printf("\t%d",i);
printf("\n");
for(i=1;i<=n;i++)
{
printf("%d\t",i);
for(j=1;j<=n;j++)
if(j==x[i])
printf("%c\t",'*');
else
printf("-\t");
printf("\n");
}
printf("\n");
}
else
Nqueen(k+1,n);
}
}
}

int place(int k,int i)


{
int j;
for(j=1;j<k;j++)
if((x[j]==i)||abs(x[j]-i)==abs(j-k))
return 0;
return 1;
}
OUTPUT

Enter the number of queens to be placed :4


The possible combinations of placing 4 queens in a 4x4 chessboard are :

1 2 3 4
1 - * - -
2 - - - *
3 * - - -
4 - - * -

1 2 3 4
1 - - * -
2 * - - -
3 - - - *
4 - * - -
PROGRAM 9

Study and analyse Floyd Warshall’s algorithm

#include<stdio.h>
#include<conio.h>
#define infinity 10000

void main( )
{
int w[10][10],q[10][10],i,j,k,m,n,s;
clrscr( );
printf("Enter the number of vertices :");
scanf("%d",&n);
printf("\nEnter the input weighted matrix<'-'for infinity>:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&w[i][j]);

for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
q[i][j] = 0;
else
if(w[i][j]==0)
q[i][j] = infinity;
else
q[i][j] = w[i][j];

for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
q[i][j] = (q[i][j]<(q[i][k]+q[k][j]))?q[i][j]:(q[i][k]+q[k][j]);

printf("The minimum path matrix is :\n");


for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
if(q[i][j]==infinity)
printf(" - ");
else
printf("%6d",q[i][j]);
printf("\n");
}
getch( );
}
OUTPUT
Enter the number of vertices :5

Enter the input weighted matrix :

0 3 8 0 -4
0 0 0 1 7
0 4 0 0 0
2 0 -5 0 0
0 0 0 6 0
The minimum path matrix is :
0 1 -3 2 -4
3 0 -4 1 -1
7 4 0 5 3
2 -1 -5 0 -2
8 5 1 6 0
PROGRAM 8

Study and analyse Dijkstra’s algorithm for single source shortest path
in a weighted graph.

#include<stdio.h>
#include<conio.h>
#include<limits.h>
int n,k;
#define perm 1
#define tent 2
#define infinity INT_MAX

typedef struct nodelabel{


int predecessor;
int length;
int label;
int number;
}nodelabel;

void initialize_single_source(nodelabel state[ ],int s,int n)


{
int i;
for(i=1;i<=n;i++)
{
state[i].predecessor = 0;
state[i].length = infinity;
state[i].label = tent;
state[i].number = i;
}
state[s].predecessor = 0;
state[s].length = 0;
state[s].label = perm;
state[s].number = s;
}

int parent(int i)
{
return i/2;
}

int left(int i)
{
return 2*i;
}

int right(int i)
{
return 2*i+1;
}

void min_heapify(nodelabel q[],int i)


{
struct nodelabel temp;
int l,r,smallest;
l = left(i);
r = right(i);
if(l<=k && q[l].length<q[i].length)
smallest = l;
else
smallest = i;
if(r<=k && q[r].length<q[i].length)
smallest = r;
if(smallest!=i)
{
temp = q[i];
q[i] = q[smallest];
q[smallest] = temp;
min_heapify(q,smallest);
}
}

void build_min_heap(nodelabel q[],int n)


{
int i;
for(i=n/2;i>=1;i--)
min_heapify(q,i);
}

nodelabel heap_extract_min(nodelabel state[])


{
nodelabel min,temp;
min = state[1];
temp = state[1];
state[1] = state[k];
state[k] = temp;
k = k-1;
min_heapify(state,1);
return min;
}

void heap_decrease_key(nodelabel state[],int key,int i)


{
nodelabel temp;
state[i].length = key;
while(i>1 && state[parent(i)].length>state[i].length)
{
temp = state[i];
state[i] = state[parent(i)];
state[parent(i)] = temp;
i = parent(i);
}
}
void relax(nodelabel u,int a[10][10],nodelabel state[],int i)
{
int key;
if(state[i].length>([Link]+a[[Link]][state[i].number]))
{
state[i].predecessor = [Link];
key = [Link]+a[[Link]][state[i].number];
heap_decrease_key(state,key,i);
}
}

void Dijkstra(int a[][10],int n,int s)


{
nodelabel state[10],min;
int i,count,j,x,dist=0;
int path[10];

initialize_single_source(state,s,n);
build_min_heap(state,n);

while(k!=0)
{
min = heap_extract_min(state);
for(i=1;i<=k;i++)
if(a[[Link]][state[i].number]>0 && state[i].label==tent)
relax(min,a,state,i);
[Link] = perm;
}

for(i=1;i<=n;i++)
if(i!=s)
{
j = i;
dist = 0;
count = 0;
do
{
count++;
path[count] = j;
for(k=1;k<=n;k++)
if(state[k].number==j)
{
j = state[k].predecessor;
break;
}
}while(j!=0);

for(j=1;j<=count/2;j++)
{
x = path[j];
path[j] = path[count-j+1];
path[count-j+1] = x;
}

for(j=1;j<count;j++)
dist +=a[path[j]][path[j+1]];

printf("\nShortest path from %d to %d is :",s,i);


if(count!=1)
printf("%d",path[1]);
else
printf("No path from %d to %d",s,i);
for(j=2;j<=count;j++)
printf("-->%d",path[j]);
printf("\nDistance from node %d to %d is : %d",s,i,dist);
printf("\n");
}
}
void main( )
{
int a[10][10],i,j,source;
clrscr( );

printf("Enter the number of nodes :");


scanf("%d",&n);

for(i=1;i<=n;i++)
{
printf("\nEnter node %d connectivity :",i);
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
}
k=n;
printf("\nEnter the source node :");
scanf("%d",&source);

Dijkstra(a,n,source);
getch( );
}
OUTPUT

Enter the number of nodes : 5


Enter node 1 connectivity :0 10 0 5 0
Enter node 2 connectivity :0 0 1 2 0
Enter node 3 connectivity :0 0 0 0 4
Enter node 4 connectivity :0 3 9 0 2
Enter node 5 connectivity :7 0 6 0 0
Enter the source node :1

Shortest path from 1 to 2 is :1-->4-->2


Distance from node 1 to 2 is : 8

Shortest path from 1 to 3 is :1-->4-->2-->3


Distance from node 1 to 3 is : 9

Shortest path from 1 to 4 is :1-->4


Distance from node 1 to 4 is : 5

Shortest path from 1 to 5 is :1-->4-->5


Distance from node 1 to 5 is : 7
PROGRAM 3

Study and analyse Prim’s and Kruskal’s algorithm to find minimum


spanning tree in a weighted graph

PRIM’S ALGORITHM
#include<stdio.h>
#include<conio.h>
#include<limits.h>
int n,k;
#define perm 1
#define tent 2
#define infinity INT_MAX

typedef struct nodelabel{


int predecessor;
int length;
int label;
int number;
}nodelabel;

void initialize_single_source(nodelabel state[ ],int s,int n)


{
int i;
for(i=1;i<=n;i++)
{
state[i].predecessor = 0;
state[i].length = infinity;
state[i].label = tent;
state[i].number = i;
}
state[s].predecessor = 0;
state[s].length = 0;
state[s].label = perm;
state[s].number = s;
}

int parent(int i)
{ return i/2;}

int left(int i)
{ return 2*i;}
int right(int i)
{ return 2*i+1;}

void min_heapify(nodelabel q[],int i)


{
struct nodelabel temp;
int l,r,smallest;
l = left(i);
r = right(i);
if(l<=k && q[l].length<q[i].length)
smallest = l;
else
smallest = i;
if(r<=k && q[r].length<q[i].length)
smallest = r;
if(smallest!=i)
{
temp = q[i];
q[i] = q[smallest];
q[smallest] = temp;
min_heapify(q,smallest);
}
}

void build_min_heap(nodelabel q[],int n)


{
int i;
for(i=n/2;i>=1;i--)
min_heapify(q,i);
}

nodelabel heap_extract_min(nodelabel state[])


{
nodelabel min,temp;
min = state[1];
temp = state[1];
state[1] = state[k];
state[k] = temp;
k = k-1;
min_heapify(state,1);
return min;
}
void heap_decrease_key(nodelabel state[],int key,int i)
{
nodelabel temp;
state[i].length = key;
while(i>1 && state[parent(i)].length>state[i].length)
{
temp = state[i];
state[i] = state[parent(i)];
state[parent(i)] = temp;
i = parent(i);
}
}
void relax(nodelabel u,int a[10][10],nodelabel state[],int i)
{
int key;
if(state[i].length>+a[[Link]][state[i].number])
{
state[i].predecessor = [Link];
key = a[[Link]][state[i].number];
heap_decrease_key(state,key,i);
}
}

void Dijkstra(int a[][10],int n,int s)


{
nodelabel state[10],min;
int i,count,j,x,dist=0;
int path[10];
initialize_single_source(state,s,n);
build_min_heap(state,n);

while(k!=0)
{
min = heap_extract_min(state);
for(i=1;i<=k;i++)
if(a[[Link]][state[i].number]>0 && state[i].label==tent)
relax(min,a,state,i);
[Link] = perm;
}
for(i=1;i<=n;i++)
if(state[i].predecessor!=0)
printf("\n%d-->%d",state[i].predecessor,state[i].number);
}
void main( )
{
int a[10][10],i,j,root;
clrscr( );
printf("Enter the number of nodes :");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter node %d connectivity :",i);
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
}
k=n;
printf("\nEnter the root node :");
scanf("%d",&root);
Dijkstra(a,n,root);
getch( );
}
OUTPUT
Enter the number of nodes :9
Enter node 1 connectivity :0 4 0 0 0 0 8 3 0
Enter node 2 connectivity :4 0 6 8 0 0 0 0 7
Enter node 3 connectivity :0 6 0 5 4 0 0 0 1
Enter node 4 connectivity :0 8 5 0 9 0 0 0 0
Enter node 5 connectivity :0 0 4 9 0 10 3 0 6
Enter node 6 connectivity :0 0 0 0 10 0 11 0 2
Enter node 7 connectivity :8 0 0 0 3 11 0 8 1
Enter node 8 connectivity :3 0 0 0 0 0 8 0 4
Enter node 9 connectivity :0 7 1 0 6 2 1 4 0
Enter the root node :1

Edges in the minimum spanning tree are :


3-->4
1-->2
7-->5
9-->6
9-->3
7-->9
1-->7
1-->8
PROGRAM 11

Study and analyse huffman coding

#include<stdio.h>
#include<conio.h>
#include<limits.h>
#define infinity INT_MIN

struct node{ int data;


char character;
struct node*lst;
struct node*rst;
struct node*parent;
};
typedef struct node *nodeptr;
nodeptr nodes[10],temp,min;
int n,k,h;

nodeptr getnode( )
{
nodeptr p;
p=(nodeptr) malloc(sizeof(struct node));
return p;
}

int parent(int i)
{
return i/2;
}

int left(int i)
{
return 2*i;
}

int right(int i)
{
return 2*i+1;
}

void min_heapify(int i)
{
int l,r,smallest;
l = left(i);
r = right(i);
if(l<=k && nodes[l]->data<nodes[i]->data)
smallest = l;
else
smallest = i;
if(r<=k && nodes[r]->data<nodes[smallest]->data)
smallest = r;
if(smallest!=i)
{
temp = nodes[i];
nodes[i] = nodes[smallest];
nodes[smallest] = temp;
min_heapify(smallest);
}
}

void build_min_heap(int n)
{
int i;
for(i=n/2;i>=1;i--)
min_heapify(i);
}

nodeptr heap_extract_min( )
{
if(k<1)
printf("\nHeap underflow\n");
min = nodes[1];
nodes[1] = nodes[k];
k = k-1;
min_heapify(1);
return min;
}

void heap_decrease_key(nodeptr z,int k)


{
int i;
i = k;
nodes[i] = z;
while(i>1 && nodes[parent(i)]->data>nodes[i]->data)
{
temp = nodes[i];
nodes[i] = nodes[parent(i)];
nodes[parent(i)] = temp;
i = parent(i);
}
}

void min_heap_insert(nodeptr z)
{
int i;
k=k+1;
nodes[k] = z;
}

void initialize_huffman(int a[],char c[],int n)


{
int i;
for(i=1;i<=n;i++)
{
nodes[i] = getnode( );
nodes[i]->data = a[i];
nodes[i]->character = c[i];
nodes[i]->lst = NULL;
nodes[i]->rst = NULL;
nodes[i]->parent = NULL;
}
}

nodeptr huffmann(int a[ ],char c[ ],int n)


{
int i;
nodeptr z=NULL,x=NULL,y=NULL;
initialize_huffman(a,c,n);
build_min_heap(n);
for(i=1;i<n;i++)
{
x=heap_extract_min( );
y=heap_extract_min( );
z = getnode( );
z->lst = x;
z->rst = y;
z->data = x->data+y->data;
x->parent = z;
y->parent = z;
z->parent = NULL;
min_heap_insert(z);
}
return(heap_extract_min( ));
}

void PrintTree(nodeptr p,int level)


{ int i;
if(p!=NULL)
{
PrintTree(p->rst,level+1);
printf("\n");
for(i=0;i<level;i++)
printf(" ");
printf(" %d ",p->data);
PrintTree(p->lst,level+1);
}
}
void postorder(nodeptr tree)
{
if(tree)
{
postorder(tree->lst);
postorder(tree->rst);
if((tree->lst==NULL)&&(tree->rst==NULL))
nodes[h++]=tree;
}
}

void main( )
{
int a[10],b[10],i,j=1,l,x;
char c[10];
nodeptr root = NULL,tree=NULL;
clrscr( );

printf("Enter the number of characters :");


scanf("%d",&n);
k = n;
h = 1;
printf("\nEnter the character :\n");
for(i=1;i<=n;i++)
scanf("%s",&c[i]);

printf("\nEnter the frequency of each character :\n");


for(i=1;i<=n;i++)
scanf("%d",&a[i]);

root = huffmann(a,c,n);
PrintTree(root,1);
tree = root;
postorder(tree);

for(i=1;i<h;i++)
{
tree = nodes[i];
j = 0;
while(tree!=root)
{
j++;
if((tree->parent)->lst==tree)
b[j] = 0;
else
b[j] = 1;
tree = tree->parent;
}
for(l=1;l<=j/2;l++)
{
x = b[l];
b[l] = b[j-l+1];
b[j-l+1] = x;
}
printf("\nThe codeword for character %c is ",nodes[i]->character);
for(l=1;l<=j;l++)
printf("%d",b[l]);
printf("\n");
}
getch( );
}
OUTPUT

Enter the number of characters :6

Enter the character :


abcdef

Enter the frequency of each character :


45 13 12 16 9 5

16
30
9
14
5
55
13
25
12
100
45

The codeword for character a is 0


The codeword for character c is 100
The codeword for character b is 101
The codeword for character f is 1100
The codeword for character e is 1101
The codeword for character d is 111
PROGRAM 12

Study and analyse radix sort

#include<stdio.h>
#include<conio.h>
void counting_sort(int A[ ][20],int n,int q);
int B[20][20];
int k,d;
void main( )
{
int n,i,A[20][20],j,l;
clrscr( );
printf("\nEnter the radix of elements in the array :");
scanf("%d",&k);
printf("\nEnter the number of elements in the array :");
scanf("%d",&n);
printf("\nEnter the number of digits in each element :");
scanf("%d",&d);
printf("Enter the elements of array(varying from 0 to %d):",k-1);
for(i=1;i<=n;i++)
for(j=1;j<=d;j++)
{
scanf("%d",&A[i][j]);
if(A[i][j]>k-1)
{
printf("\nNot an allowed input\n");
getch( );
exit(0);
}
}

for(i=d;i>=1;i--)
{
counting_sort(A,n,i);
for(l=1;l<=n;l++)
for(j=1;j<=d;j++)
A[l][j] = B[l][j];
}
printf("Elements in sorted array are :");
for(l=1;l<=n;l++)
{
printf("\n");
for(j=1;j<=d;j++)
printf("%d ",A[l][j]);
}
}

void counting_sort(int A[ ][20],int n,int q)


{
int l,j,C[20];
for(l=0;l<=k;l++)
C[l] = 0;
for(j=1;j<=n;j++)
C[A[j][q]] = C[A[j][q]]+1;
for(l=1;l<=k;l++)
C[l] = C[l]+C[l-1];
for(j=n;j>=1;j--)
{
for(l=1;l<=d;l++)
B[C[A[j][q]]][l] = A[j][l];
C[A[j][q]] = C[A[j][q]]-1;
}
}
OUTPUT

Enter the radix of elements in the array :10


Enter the number of elements in the array :6
Enter the number of digits in each element :3
Enter the elements of array(varying from 0 to 9):
546
987
214
654
321
741
Elements in sorted array are :
214
321
546
654
741
987

You might also like