0% found this document useful (0 votes)
82 views

ADA Practical Solution

The document describes programs to implement various algorithms for sorting and searching arrays in C language. It includes programs for inserting elements into an array, sorting arrays using bubble, selection and insertion sort algorithms, and searching an element in an array using sequential/linear search. For each algorithm, it provides the C code implementation and sample output showing it works as expected.

Uploaded by

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

ADA Practical Solution

The document describes programs to implement various algorithms for sorting and searching arrays in C language. It includes programs for inserting elements into an array, sorting arrays using bubble, selection and insertion sort algorithms, and searching an element in an array using sequential/linear search. For each algorithm, it provides the C code implementation and sample output showing it works as expected.

Uploaded by

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

Analysis And Design of Algorithms

1. Write a program to implement insert data into Array and display Array.
#include<stdio.h>

#include<conio.h>

void main()

int n, a[20], temp, i, j;

clrscr();

printf("=========Array===========");

printf("\n Enter the number of Elements you want to insert: ");

scanf(“%d”,&n);

// Input Array

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

printf("Enter the element a[%d]: ",i);

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

// Output Display Array

printf("\n\n Array Elements:\n");

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

printf(“a[%d]:”,i);

printf(“%d\n”,a[i]);

getch();

1|P ag e
Analysis And Design of Algorithms

Output

========= Array===========

Enter the number of Elements you want to insert:10

Enter the element a[0]: 70

Enter the element a[1]: 30

Enter the element a[2]: 20

Enter the element a[3]: 50

Enter the element a[4]: 60

Enter the element a[5]: 10

Enter the element a[6]: 40

Enter the element a[7]: 80

Enter the element a[8]: 05

Enter the element a[9]: 90

Array Elements

a[0]:70

a[1]:30

a[2]:20

a[3]:50

a[4]:60

a[5]:10

a[6]:40

a[7]:80

a[8]:05

a[9]:90

2|P ag e
Analysis And Design of Algorithms

2. Write a program to implement the Bubble Sort Method.


#include<stdio.h>

#include<conio.h>

void main()

int n, a[20], temp, i, j;

clrscr();

printf("=========Bubble Sort Algorithm===========");

printf("\n Enter the number of Elements you want to sort: ");

scanf(“%d”,&n);

// Input Array

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

printf("Enter the element a[%d]: ",i);

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

// Bubble Sort Algorithm Process

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

for(j=0;j<=n-2-i;j++)

if(a[j]>a[j+1])

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

3|P ag e
Analysis And Design of Algorithms

// Output Display Array

printf("\n\n Sorted Elements:\n");

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

printf(“a[%d]:”,i);

printf(“%d\n”,a[i]);

getch();

4|P ag e
Analysis And Design of Algorithms

Output

========= Bubble Sort Algorithm ===========

Enter the number of Elements you want to sort:10

Enter the element a[0]: 70

Enter the element a[1]: 30

Enter the element a[2]: 20

Enter the element a[3]: 50

Enter the element a[4]: 60

Enter the element a[5]: 10

Enter the element a[6]: 40

Enter the element a[7]: 80

Enter the element a[8]: 05

Enter the element a[9]: 90

Sorted Elements

a[0]:05

a[1]:10

a[2]:20

a[3]:30

a[4]:40

a[5]:50

a[6]:60

a[7]:70

a[8]:80

a[9]:90

5|P ag e
Analysis And Design of Algorithms

3. Write a program to implement the Selection Sort Method.


#include<stdio.h>

#include<conio.h>

void main()

int n, a[20], temp,min, i, j;

clrscr();

printf("=========Selection Sort Algorithm===========");

printf("\n Enter the number of Elements you want to sort: ");

scanf(“%d”,&n);

// Input Array

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

printf("Enter the element a[%d]: ",i);

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

// Selection Sort Algorithm Process

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

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

if(a[j]<a[min])

min=j;

temp=a[i];

a[i]=a[min];

a[min]=temp;

6|P ag e
Analysis And Design of Algorithms

// Output Display Array

printf("\n\n Sorted Elements:\n");

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

printf(“a[%d]:”,i);

printf(“%d\n”,a[i]);

getch();

7|P ag e
Analysis And Design of Algorithms

Output

========= Selection Sort Algorithm ===========

Enter the number of Elements you want to sort:10

Enter the element a[0]: 70

Enter the element a[1]: 30

Enter the element a[2]: 20

Enter the element a[3]: 50

Enter the element a[4]: 60

Enter the element a[5]: 10

Enter the element a[6]: 40

Enter the element a[7]: 80

Enter the element a[8]: 05

Enter the element a[9]: 90

Sorted Elements

a[0]:05

a[1]:10

a[2]:20

a[3]:30

a[4]:40

a[5]:50

a[6]:60

a[7]:70

a[8]:80

a[9]:90

8|P ag e
Analysis And Design of Algorithms

4. Write a program to implement the Insertion Sort Method.


#include<stdio.h>

#include<conio.h>

void main()

int n, a[20], key , i, j;

clrscr();

printf("=========Insertion Sort Algorithm===========");

printf("\n Enter the number of Elements you want to sort: ");

scanf(“%d”,&n);

// Input Array

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

printf("Enter the element a[%d]:",i);

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

// Insertion Sort Algorithm Process

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

Key=a[i];

for(j=i-1;j>=0;j--)

if(a[j]>key)

a[j+1]=a[j];

a[j]=key;

9|P ag e
Analysis And Design of Algorithms

// Output Display Array

printf("\n\n Sorted Elements:\n");

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

printf(“a[%d]:”,i);

printf(“%d\n”,a[i]);

getch();

10 | P a g e
Analysis And Design of Algorithms

Output

========= Insertion Sort Algorithm ===========

Enter the number of Elements you want to sort:10

Enter the element a[0]: 70

Enter the element a[1]: 30

Enter the element a[2]: 20

Enter the element a[3]: 50

Enter the element a[4]: 60

Enter the element a[5]: 10

Enter the element a[6]: 40

Enter the element a[7]: 80

Enter the element a[8]: 05

Enter the element a[9]: 90

Sorted Elements

a[0]:05

a[1]:10

a[2]:20

a[3]:30

a[4]:40

a[5]:50

a[6]:60

a[7]:70

a[8]:80

a[9]:90

11 | P a g e
Analysis And Design of Algorithms

5. Write a program to search key using Sequential / Linear Search Method.


#include<stdio.h>

#include<conio.h>

void main()

int n, a[20], key , i, j;

clrscr();

printf("=========Sequential Search===========");

printf("\n Enter the number of Elements: ");

scanf(“%d”,&n);

// Input Array

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

printf("Enter the element a[%d]:",i);

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

printf(“Enter the element which is to be searched:”);

scanf(“%d”,&key);

// Sequential Search Algorithm Process

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

if(a[i]==key)

printf(“\n The element you want to search is found at location a[%d]”,i);

break;

getch();

12 | P a g e
Analysis And Design of Algorithms

Output

========= Sequential Search ===========

Enter the number of Elements:10

Enter the element a[0]: 70

Enter the element a[1]: 30

Enter the element a[2]: 20

Enter the element a[3]: 50

Enter the element a[4]: 60

Enter the element a[5]: 10

Enter the element a[6]: 40

Enter the element a[7]: 80

Enter the element a[8]: 05

Enter the element a[9]: 90

Enter the element which is to be searched: 50

The element you want to search is found at location a[3]

13 | P a g e
Analysis And Design of Algorithms

6. Write a program to search key using Binary Search Method.


#include<stdio.h>

#include<conio.h>

void main()

int n, a[20], key , i, low, high, mid;

clrscr();

printf("=========Binary Search===========");

printf("\n Enter the number of Elements: ");

scanf(“%d”,&n);

// Input Array

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

printf("Enter the element a[%d]:",i);

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

printf(“Enter the element which is to be searched:”);

scanf(“%d”,&key);

// Binary Search Algorithm Process

low=0;

high=n-1;

while(low<=high)

mid=(low+high)/2;

if(key==a[mid])

printf(“Search key found at location a[%d]”,mid);

break;

14 | P a g e
Analysis And Design of Algorithms

else if(key>a[mid])

low=mid+1;

else

high=mid-1;

getch();

Output

========= Binary Search ===========

Enter the number of Elements:5

Enter the element a[0]: 10

Enter the element a[1]: 20

Enter the element a[2]: 30

Enter the element a[3]: 50

Enter the element a[4]: 60

Enter the element which is to be searched: 50

The element you want to search is found at location a[3]

15 | P a g e
Analysis And Design of Algorithms

7. Write a program to search key using Binary Search Method using Divide and
Conquer.
#include<stdio.h>

#include<conio.h>

#define size 20

int n;

void main()

int a[size],key,i,flag,low,high;

int bin_search(int a[size],int,int,int);

clrscr();

printf("=========Binary Search===========");

printf("\n Enter the number of Elements: ");

scanf(“%d”,&n);

// Input Array

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

printf("Enter the element a[%d]:",i);

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

printf(“Enter the element which is to be searched:”);

scanf(“%d”,&key);

low=0;

high=n-1;

flag=bin_search(a,key,low,high);

printf("\n The element you want to search is found at location a[%d] ",flag);

getch();

16 | P a g e
Analysis And Design of Algorithms

int bin_search(int a[size],int key,int low,int high)

int m;

m=(low+high)/2; //mid of the array is obtained

if(key==a[m])

return m;

else if(key<a[m])

bin_search(a,key,low,m-1);//search the left sub list

else

bin_search(a,key,m+1,high);//search the right sub list

Output
========= Binary Search ===========

Enter the number of Elements:5

Enter the element a[0]: 10

Enter the element a[1]: 20

Enter the element a[2]: 30

Enter the element a[3]: 50

Enter the element a[4]: 60

Enter the element which is to be searched: 50

The element you want to search is found at location a[3]

17 | P a g e
Analysis And Design of Algorithms

8. Write a program to implement Merge Sort using Divide and Conquer.

#include<stdio.h>

#include<conio.h>

void MergeSort(int [],int,int);

void Combine(int [],int,int);

void main()

int n, a[20], low,high, i, j;

clrscr();

printf("=========Merge Sort Algorithm===========");

printf("\n Enter the number of Elements you want to sort: ");

scanf(“%d”,&n);

// Input Array

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

printf("Enter the element a[%d]:- ",i);

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

low=1, high=n;

MergeSort(a,low,high);

// Output Display Array

printf("\n\n Sorted Elements:\n");

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

printf(“a[%d]:”,i);

printf(“%d\n”,a[i]);

getch();

18 | P a g e
Analysis And Design of Algorithms

void MergeSort(int a[10], int low, int high)

int mid;

if(low<high)

mid=(low+high)/2;

MergeSort(a,low,mid);

MergeSort(a,mid+1,high);

Combine(a,low,mid,high);

}
}

void Combine(int a[10], int low, int mid, int high)

int i,j,k;

int temp[10];

k=low;

i=low;

j=mid+1;

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

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

temp[k]=a[i];

i++;

k++;

else

temp[k]=a[j];

j++;

19 | P a g e
Analysis And Design of Algorithms

k++;

while(i<=mid)

temp[k]=a[i];

i++;

k++;

while(j<=mid)

temp[k]=a[j];

j++;

k++;

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

a[k]=temp[k];

20 | P a g e
Analysis And Design of Algorithms

Output

========= Merge Sort Algorithm ===========

Enter the number of Elements you want to sort:10

Enter the element a[0]: 70

Enter the element a[1]: 30

Enter the element a[2]: 20

Enter the element a[3]: 50

Enter the element a[4]: 60

Enter the element a[5]: 10

Enter the element a[6]: 40

Enter the element a[7]: 80

Enter the element a[8]: 05

Enter the element a[9]: 90

Sorted Elements

a[0]:05

a[1]:10

a[2]:20

a[3]:30

a[4]:40

a[5]:50

a[6]:60

a[7]:70

a[8]:80

a[9]:90

21 | P a g e
Analysis And Design of Algorithms

9. Write a program to implement Quick Sort using Divide and Conquer.


#include<stdio.h>

#include<conio.h>

#define size 20

void quick(int a[size],int,int);

int partition(int a[size],int,int);

void swap(int a[size],int *,int *);

int n;

void main()

int i;

int a[size];

clrscr();

printf("\nEnter Total numbers to sort: ");

scanf("%d",&n);

printf("\nEnter %d numbers: ",n);

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

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

quick(a,0,n-1);

printf("\nSorted array is :\n\n");

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

printf("\t%d",a[i]);

getch();

void quick(int a[size],int low,int high)

int m,i;

if(low<high)

m=partition(a,low,high);//setting pivot element

22 | P a g e
Analysis And Design of Algorithms

quick(a,low,m-1);//spliting of list

quick(a,m+1,high);//spiting of list

int partition(int a[size],int low,int high)

int pivot=a[low],i=low,j=high;

while(i<=j)

while(a[i]<=pivot)i++;

while(a[j]>pivot)j--;

if(i<j)swap(a,&i,&j);

swap(a,&low,&j);

return j;

void swap(int a[size],int *i,int *j)

int temp;

temp=a[*i];

a[*i]=a[*j];

a[*j]=temp;

23 | P a g e
Analysis And Design of Algorithms

Output

Enter Total numbers to sort: 5

Enter 5 numbers: 80 70 90 30 10

Sorted array is :

10 30 70 80 90

24 | P a g e
Analysis And Design of Algorithms

10. Write a program to implement addition of two matrices.


#include<stdio.h>

#include<conio.h>

void main()

int a[2][2],b[2][2],c[2][2],i,j;

clrscr();

printf("=========Matrix Addition===========");

printf("\nEnter the value of first Array:-\n");

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

for(j=0;j<2;j++)

printf("Enter the element a[%d][%d]:- ",i,j);

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

c[i][j]=0;

printf("Enter the value of second Array:- \n");

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

for(j=0;j<2;j++)

printf("Enter the element b[%d][%d]:- ",i,j);

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

printf("\n\n\n The Addition of two matrices is :-\n\n");

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

25 | P a g e
Analysis And Design of Algorithms

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

c[i][j]=a[i][j]+b[i][j];

printf("\t%d",c[i][j]);

printf("\n\n");

getch();

Output
=========Matrix Addition===========

Enter the value of first Array:-

Enter the element a[0][0]:- 1

Enter the element a[0][1]:- 2

Enter the element a[1][0]:- 3

Enter the element a[1][1]:- 4

Enter the value of second Array:-

Enter the element b[0][0]:- 5

Enter the element b[0][1]:- 6

Enter the element b[1][0]:- 7

Enter the element b[1][1]:- 8

The Addition of two matrices is :-

6 8

10 12

26 | P a g e
Analysis And Design of Algorithms

11. Write a program to implement multiplication of two matrices.


#include<stdio.h>

#include<conio.h>

void main()

int a[2][2],b[2][2],c[2][2],i,j,k;

clrscr();

printf("=========Matrix Multiplication===========");

printf("\nEnter the value of first Array:-\n");

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

for(j=0;j<2;j++)

printf("Enter the element a[%d][%d]:- ",i,j);

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

c[i][j]=0;

printf("Enter the value of second Array:-\n");

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

for(j=0;j<2;j++)

printf("Enter the element b[%d][%d]:- ",i,j);

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

printf("\n\n\n The Multiplication of two matrices are:-\n\n");

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

27 | P a g e
Analysis And Design of Algorithms

for(j=0;j<2;j++)

c[i][j]=0;

for(k=0;k<2;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

printf("\t%d",c[i][j]);

printf("\n\n");

getch();

28 | P a g e
Analysis And Design of Algorithms

Output
=========Matrix Multiplication===========

Enter the value of first Array:-

Enter the element a[0][0]:- 1

Enter the element a[0][1]:- 2

Enter the element a[1][0]:- 3

Enter the element a[1][1]:- 4

Enter the value of second Array:-

Enter the element b[0][0]:- 5

Enter the element b[0][1]:- 6

Enter the element b[1][0]:- 7

Enter the element b[1][1]:- 8

The Multiplication of two matrices are:-

19 22

43 50

29 | P a g e
Analysis And Design of Algorithms

12. Write a program to implement strassion matrices multiplication using Divide and
Conquer strategy.
//Matrix multiplication using strassion multiplication

#include<stdio.h>

#include<conio.h>

void main()

int a[3][3],b[3][3],i,j;

int s1,s2,s3,s4,s5,s6,s7;

int c[3][3];

clrscr();

printf("=========Matrix Multiplication===========");

printf("\nEnter the value of first Array:-\n");

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

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

printf("Enter the element a[%d][%d]:- ",i,j);

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

printf("Enter the value of second Array:-\n");

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

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

printf("Enter the element b[%d][%d]:- ",i,j);

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

30 | P a g e
Analysis And Design of Algorithms

s1=(a[1][1]+a[2][2])*(b[1][1]+b[2][2]);

s2=(a[2][1]+a[2][2])*b[1][1];

s3=a[1][1]*(b[1][2]-b[2][2]);

s4=a[2][2]*(b[2][1]-b[1][1]);

s5=(a[1][1]+a[1][2])*b[2][2];

s6=(a[2][1]-a[1][1])*(b[1][1]+b[1][2]);

s7=(a[1][2]-a[2][2])*(b[2][1]+b[2][2]);

c[1][1]=s1+s4-s5+s7;

c[1][2]=s3+s5;

c[2][1]=s2+s4;

c[2][2]=s1+s3-s2+s6;

printf("\n\n\n The Multiplication of two matrices is:-\n\n");

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

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

printf("\t%d",c[i][j]);

printf("\n\n");

getch();

31 | P a g e
Analysis And Design of Algorithms

Output

=========Matrix Multiplication===========

Enter the value of first Array:-

Enter the element a[1][1]:- 1

Enter the element a[1][1]:- 2

Enter the element a[1][1]:- 3

Enter the element a[1][1]:- 4

Enter the value of Second Array:-

Enter the element b[1][1]:- 5

Enter the element b[1][1]:- 6

Enter the element b[1][1]:- 7

Enter the element b[1][1]:- 8

The Multiplication of two matrices is:-

19 22

43 50

32 | P a g e
Analysis And Design of Algorithms

13. Write a program to implement Exponential of two numbers using Divide and
Conquer.
#include<stdio.h>
#include<conio.h>
int exp(int,int);
void main()
{

int x,n;

clrscr();

printf("Exponentiation (x,n)\n");

printf("Enter x: ");

scanf("%d",&x);

printf("Enter n: ");

scanf("%d",&n);

printf("Exponentiation (%d,%d) = %d",x,n,exp(x,n));

getch();

int exp(int x,int n)

if(n==0)

return 1;

if(n%2==0)

return (exp(x,n/2)* exp(x,n/2));

else

return (x* exp(x,n/2)* exp(x,n/2));

Output
Exponentiation (x,n)

Enter x: 5

Enter n: 3

Exponentiation (5, 3) = 125

33 | P a g e
Analysis And Design of Algorithms

14. Write a program to implement Prim’s Algorithm using Greedy method.


#include<stdio.h>

#include<conio.h>

#define SIZE 20

#define INFINITY 32767

void Prim(int [][SIZE],int);

void main()

int G[SIZE][SIZE],nodes,edges;

int v1,v2,length,i,j;

clrscr();

printf("\n============= Prim's Algorithm ====================\n");

printf("\n Enter Number of Nodes in The Graph:- ");

scanf("%d",&nodes);

printf("\n Enter Number of Edges in The Graph:- ");

scanf("%d",&edges);

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

for(j=0;j<nodes;j++)

G[i][j]=0;

printf("\n Enter edges and weights: \n");

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

printf("\n Enter Edges by V1 and V2:");

printf(" [Read the graph from starting nodes 0]: ");

scanf("%d %d",&v1,&v2);

printf("\n Enter corresponding weight: ");

scanf("%d",&length);

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

34 | P a g e
Analysis And Design of Algorithms

getch();

printf("\n\t");

clrscr();

Prim(G,nodes);

getch();

void Prim(int G[][SIZE],int nodes)

int tree[SIZE],i,j,k;

int min_dist,v1,v2,total=0;

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

tree[i]=0;

printf("\n\n The Minimal Spanning Tree Is :\n");

tree[0]=1;

for(k=1;k<=nodes-1;k++)

min_dist=INFINITY;

for(i=0;i<=nodes-1;i++)

for(j=0;j<=nodes-1;j++)

if(G[i][j]*((tree[i]&&!tree[j])||(!tree[i]&&tree[j])))

if(G[i][j]<min_dist)

min_dist=G[i][j];

v1=i;

v2=j;

35 | P a g e
Analysis And Design of Algorithms

printf("\n Edge (%d %d) and weight=%d",v1,v2,min_dist);

tree[v1]=tree[v2]=1;

total=total+min_dist;

printf("\n\n\t Total Path Length Is =%d",total);

36 | P a g e
Analysis And Design of Algorithms

Output

============= Prim's Algorithm ====================

Enter Number of Nodes in The Graph:- 5

Enter Number of Edges in The Graph:- 7

Enter edges and weights:

Enter Edges by V1 and V2: [Read the graph from starting nodes 0]: 0 1

Enter corresponding weight: 10

Enter Edges by V1 and V2: [Read the graph from starting nodes 0]: 1 2

Enter corresponding weight: 1

Enter Edges by V1 and V2: [Read the graph from starting nodes 0]: 2 3

Enter corresponding weight: 2

Enter Edges by V1 and V2: [Read the graph from starting nodes 0]: 3 4

Enter corresponding weight: 3

Enter Edges by V1 and V2: [Read the graph from starting nodes 0]: 4 0

Enter corresponding weight: 5

Enter Edges by V1 and V2: [Read the graph from starting nodes 0]: 1 3

Enter corresponding weight: 6

Enter Edges by V1 and V2: [Read the graph from starting nodes 0]: 4 2

Enter corresponding weight: 7

The Minimal Spanning Tree Is :

Edge (0 4) and weight=5

Edge (3 4) and weight=3

Edge (2 3) and weight=2

Edge (1 2) and weight=1

Total Path Length Is =11

37 | P a g e
Analysis And Design of Algorithms

15. Write a program to implement Kruskal’s Algorithm using Greedy method.


#include<stdio.h>

#include<conio.h>

#define INFINITY 990

typedef struct Graph

int v1;

int v2;

int cost;

}GR;

GR G[20];

int tot_edges,tot_nodes;

void create();

void spanning_tree();

int Minimum(int);

void main()

clrscr();

printf("\n\t Graph Creation by adjacenvy matrix");

create();

spanning_tree();

getch();

void create()

int k;

printf("\n Enter Total number of nodes: ");

scanf("%d",&tot_nodes);

printf("\n Enter Total number of edges: ");

scanf("%d",&tot_edges);

38 | P a g e
Analysis And Design of Algorithms

for(k=0;k<=tot_edges-1;k++)

printf("\n Enter Edge in (V1 V2) form: ");

scanf("%d %d",&G[k].v1,&G[k].v2);

printf("\n Enter Corresponding Cost: ");

scanf("%d",&G[k].cost);

void spanning_tree()

int count,k,v1,v2,i,j,tree[10][10],pos,parent[10],sum;

int Find(int v2,int parent[]);

void Union(int i,int j,int parent[]);

count=0;

k=0;

sum=0;

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

parent[i]=i;

while(count!=tot_nodes-1)

pos=Minimum(tot_edges);

if(pos==-1)

break;

v1=G[pos].v1;

v2=G[pos].v2;

i=Find(v1,parent);

39 | P a g e
Analysis And Design of Algorithms

j=Find(v2,parent);

if(i!=j)

tree[k][0]=v1;

tree[k][1]=v2;

k++;

count++;

sum+=G[pos].cost;

Union(i,j,parent);

G[pos].cost=INFINITY;

if(count==tot_nodes-1)

printf("\n Spanning tree is..");

printf("\n-------------------\n");

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

printf("[%d",tree[i][0]);

printf("-");

printf("%d",tree[i][1]);

printf("]");

printf("\n----------------------");

printf("\nCost of Spanning Tree is = %d",sum);

else

printf("There is no Spanning Tree");

40 | P a g e
Analysis And Design of Algorithms

int Minimum(int n)

int i,small,pos;

small=INFINITY;

pos=-1;

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

if(G[i].cost<small)

small=G[i].cost;

pos=i;

return pos;

int Find(int v2,int parent[])

while(parent[v2]!=v2)

v2=parent[v2];

return v2;

void Union(int i,int j,int parent[])

if(i<j)

parent[j]=i;

41 | P a g e
Analysis And Design of Algorithms

else

parent[i]=j;

Output
Graph Creation by adjacenvy matrix

Enter Total number of nodes: 5

Enter Total number of edges: 6

Enter Edge in (V1 V2) form: 0 1

Enter Corresponding Cost: 5

Enter Edge in (V1 V2) form: 0 2

Enter Corresponding Cost: 11

Enter Edge in (V1 V2) form: 1 3

Enter Corresponding Cost: 7

Enter Edge in (V1 V2) form: 1 4

Enter Corresponding Cost: 9

Enter Edge in (V1 V2) form: 2 4

42 | P a g e
Analysis And Design of Algorithms

Enter Corresponding Cost: 10

Enter Edge in (V1 V2) form: 3 4

Enter Corresponding Cost: 8

Spanning tree is..

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

[0-1][1-3][3-4][2-4]

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

Cost of Spanning Tree is = 30

43 | P a g e
Analysis And Design of Algorithms

16. Write a program to implement Dijkstra’s Algorithm using Greedy Method.


#include<stdio.h>

#include<conio.h>

#define INFINITY 999

int path[20];

void disp(int s,int d,int dist[20])

int i;

for(i=d;i!=s;i=path[i])

printf("%d<-",i);

printf("%d",i);

printf(" The length = %d\n\n",dist[d]);

void dij(int tn,int cost[20][20],int s,int dist[20])

int i,j,v1,v2,md;

int sr[10];

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

dist[i]=cost[s][i];

sr[i]=0;

path[i]=s;

sr[s]=1;

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

md=INFINITY;

44 | P a g e
Analysis And Design of Algorithms

v1=-1;

for(j=0;j<tn;j++)

if(sr[j]==0)

if(dist[j]<md)

md=dist[j];

v1=j;

sr[v1]=1;

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

if(sr[v2]==0)

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

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

path[v2]=v1;

void main()

int tn,te,val,i,j,k,cost[20][20],dist[20],s[20],c=0;

clrscr();

45 | P a g e
Analysis And Design of Algorithms

printf("\nCreation of graph");

printf("\nEnter total number of nodes: ");

scanf("%d",&tn);

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

for(j=0;j<=tn;j++)

if(i==j)

cost[i][j]=0;

else

cost[i][j]=INFINITY;

printf("\n Enter Total Number of Edges: ");

scanf("%d",&te);

while(c<te)

printf("\n Enter Vi,Vj: ");

scanf("%d %d",&i,&j);

printf("\n Enter the cost along this edges: ");

scanf("%d",&val);

cost[j][i]=val;

cost[i][j]=val;

c++;

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

printf("\n\t\t Press any key to continue.....");

getch();

46 | P a g e
Analysis And Design of Algorithms

printf("\n\t\t When source = %d\n",i);

printf("\n Step by Step shortest path is...\n");

for(j=0;j<tn;j++)

dij(tn,cost,i,dist);

if(dist[j]==INFINITY)

printf("\n There is no path to %d\n",j);

else

disp(i,j,dist);

getch();

47 | P a g e
Analysis And Design of Algorithms

Output

Creation of graph

Enter total number of nodes: 5

Enter Total Number of Edges: 6

Enter Vi,Vj: 0 1

Enter the cost along this edges: 5

Enter Vi,Vj: 0 2

Enter the cost along this edges: 11

Enter Vi,Vj: 1 3

Enter the cost along this edges: 7

Enter Vi,Vj: 1 4

Enter the cost along this edges: 9

Enter Vi,Vj: 2 4

Enter the cost along this edges: 10

Enter Vi,Vj: 3 4

Enter the cost along this edges: 8

Press any key to continue.....

When source = 0

Step by Step shortest path is...

48 | P a g e
Analysis And Design of Algorithms

0 The length = 0

1<-0 The length = 5

2<-0 The length = 11

3<-1<-0 The length = 12

4<-1<-0 The length = 14

Press any key to continue.....

When source = 1

Step by Step shortest path is...

0<-1 The length = 5

1 The length = 0

2<-0<-1 The length = 16

3<-1 The length = 7

4<-1 The length = 9

Press any key to continue.....

When source = 2

Step by Step shortest path is...

0<-2 The length = 11

1<-0<-2 The length = 16

2 The length = 0

3<-4<-2 The length = 18

4<-2 The length = 10

49 | P a g e
Analysis And Design of Algorithms

Press any key to continue.....

When source = 3

Step by Step shortest path is...

0<-1<-3 The length = 12

1<-3 The length = 7

2<-4<-3 The length = 18

3 The length = 0

4<-3 The length = 8

Press any key to continue.....

When source = 4

Step by Step shortest path is...

0<-1<-4 The length = 14

1<-4 The length = 9

2<-4 The length = 10

3<-4 The length = 8

4 The length = 0

50 | P a g e
Analysis And Design of Algorithms

17. Write a program to implement Knapsack Problem using Greedy Method.


#include<stdio.h>

#include<conio.h>

struct object

float weight;

float profit;

float ratio;

}obj[50];

void knapsack(float,int);

void main()

int i,n;

float W;

clrscr();

printf("Enter capacity of knapsack: ");

scanf("%f",&W);

printf("\nEnter no of objects: ");

scanf("%d",&n);

printf("\n");

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

printf("\nObject-%d",i+1);

printf("\n\tWeight : ");

scanf("%f",&obj[i].weight);

printf("\n\tProfit : ");

scanf("%f",&obj[i].profit);

obj[i].ratio=obj[i].profit/obj[i].weight;

knapsack(W,n);

51 | P a g e
Analysis And Design of Algorithms

getch();

void knapsack(float W,int n)

int i;

float x[50],weight,profit=0;

weight=0;

i=0;

while(weight<W && i<=n-1)

x[i]=0;

if(weight+obj[i].weight<=W)

x[i]=1;

weight=weight+obj[i].weight;

else

x[i]=(float)(W-weight)/obj[i].weight;

weight=W;

profit=profit+x[i]*obj[i].profit;

i++;

printf("\n\n\t\tProfit= %f ",profit);

52 | P a g e
Analysis And Design of Algorithms

Output

Enter capacity of knapsack: 20

Enter no of objects: 3

Object-1

Weight : 15

Profit : 20

Object-2

Weight : 3

Profit : 3

Object-3

Weight : 5

Profit : 2

Profit= 23.799999

53 | P a g e
Analysis And Design of Algorithms

18. Write a program to implement Binomial Coefficient using Dynamic Programming.


// Implement Program for computing Binomial coefficient C(n,k)

#include<stdio.h>

#include<conio.h>

#define MAX 10

int Binomial(int,int);

void main()

int n,k;

clrscr();

printf("\n Enter the value of n and k=");

scanf("%d%d",&n,&k);

printf("\n The Binomial Coefficient? ");

printf("C(%d,%d)=%d",n,k,Binomial(n,k));

getch();

int Binomial(int n,int k)

int i,j,C[MAX][MAX];

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

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

C[i][j]=0;

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

for(j=0;j<=k;j++)

54 | P a g e
Analysis And Design of Algorithms

if((j==0)||(i==j))

C[i][j]=1;

else

C[i][j]=C[i-1][j-1]+C[i-1][j];

return C[n][k];

Output

Enter the value of n and k=7 2

The Binomial Coefficient? C(7,2)=21

55 | P a g e
Analysis And Design of Algorithms

19. Write a program to implement Assembly Line Scheduling using Dynamic


Programming.

#include<stdio.h>

#include<conio.h>

void main()

int n,e[3],x[3],t[3][20],f1[20],f2[20];

int l1[20],l2[20],f_star,l_star,i,j,a[3][20];

clrscr();

printf("Enter the entry time for line-1 and line-2 : ");

scanf("%d%d",&e[1],&e[2]);

printf("Enter the exit time for line-1 and line-2 : ");

scanf("%d%d",&x[1],&x[2]);

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

scanf("%d",&n);

printf("Enter the manufacturing cost at each node:\n\n");

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

printf("a[1][%d]: ",i);

scanf("%d",&a[1][i]);

printf("\n");

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

printf("a[2][%d]: ",i);

scanf("%d",&a[2][i]);

56 | P a g e
Analysis And Design of Algorithms

printf("\nEnter the switching time\n");

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

printf("t[1][%d]: ",i);

scanf("%d",&t[1][i]);

printf("\n");

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

printf("t[2][%d]: ",i);

scanf("%d",&t[2][i]);

f1[1]=e[1]+a[1][1];

f2[1]=e[2]+a[2][1];

if(f1[1]<=f2[1])

l1[1]=1;

else

l2[1]=1;

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

if(f1[j-1]+a[1][j]<=f2[j-1]+t[2][j-1]+a[1][j])

f1[j]=f1[j-1]+a[1][j];

l1[j]=1;

else

57 | P a g e
Analysis And Design of Algorithms

f1[j]=f2[j-1]+t[2][j-1]+a[1][j];

l1[j]=2;

if(f2[j-1]+a[2][j]<=f1[j-1]+t[1][j-1]+a[2][j])

f2[j]=f2[j-1]+a[2][j];

l2[j]=2;

else

f2[j]=f1[j-1]+t[1][j-1]+a[2][j];

l2[j]=1;

if(f1[n]+x[1]<=f2[n]+x[2])

f_star=f1[n]+x[1];

l_star=1;

else

f_star=f2[n]+x[2];

l_star=2;

printf("\nFASTEST TIME = %d\n",f_star);

printf("\nSTATION\tLINE\n");

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

58 | P a g e
Analysis And Design of Algorithms

if(l_star==1)

printf("\n %d\t %d",i-1,l1[i]);

getch();

Output
Enter the entry time for line-1 and line-2 : 4 2

Enter the exit time for line-1 and line-2 : 3 7

Enter the total number of nodes : 6

Enter the manufacturing cost at each node:

a[1][1]: 2

a[1][2]: 8

a[1][3]: 9

a[1][4]: 3

a[1][5]: 4

a[1][6]: 1

a[2][1]: 6

a[2][2]: 11

a[2][3]: 2

a[2][4]: 2

a[2][5]: 7

a[2][6]: 3

59 | P a g e
Analysis And Design of Algorithms

Enter the switching time

t[1][1]: 3

t[1][2]: 1

t[1][3]: 2

t[1][4]: 1

t[1][5]: 3

t[2][1]: 3

t[2][2]: 4

t[2][3]: 1

t[2][4]: 1

t[2][5]: 3

FASTEST TIME = 28

STATION LINE

1 1

2 1

3 2

4 2

5 1

6 2

60 | P a g e
Analysis And Design of Algorithms

20. Write a Program to implement Making Change Problem using Dynamic


Programming.
#include<stdio.h>

#include<conio.h>

#define INFINITY 999

int n,d[100],c[100][100];

int min(int a,int b)

if(a<=b)

return(a);

else

return(b);

Int no_of_coins(int N)

inti,j;

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

c[i][0]=0;

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

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

if(i==1 && j<d[i])

c[i][j]=INFINITY;

else if(i==1)

61 | P a g e
Analysis And Design of Algorithms

c[i][j]=1+c[1][j-d[1]];

else if(j<d[i])

c[i][j]=c[i-1][j];

else

c[i][j]=min(c[i-1][j],1+c[i][j-d[i]]);

return(c[n][N]);

void main()

inti,j,N;

clrscr();

printf("Enter total number of coins:");

scanf("%d",&n);

printf("Enter the amount of each coin in ascending order:\n");

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

printf("d[%d]:",i);

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

printf("Enter the amount for which you want change:");

scanf("%d",&N);

printf("Total number of coins required to make change of %d is %d",N,no_of_coins(N));

getch();
}

62 | P a g e
Analysis And Design of Algorithms

Output

Enter total number of coins:3

Enter the amount of each coin in ascending order:

d[1]:1

d[2]:4

d[3]:6

Enter the amount for which you want change:9

Total number of coins required to make change of 9 is 3

63 | P a g e
Analysis And Design of Algorithms

21. Write a program to implement Knapsack Problem using Dynamic Programming.

#include<stdio.h>

#include<conio.h>

#include<math.h>

int max(inta,int b)

if(a>=b)

return(a);

else

return(b);

intdynamic_knap(intn,intW,int w[20],int v[20])

intk,j,i,t[100][100];

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

for(j=0;j<=W;j++)

t[i][0]=0;

t[0][j]=0;

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

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

if(j<w[i])

t[i][j]=t[i-1][j];

else if(j>=w[i])

t[i][j]=max(t[i-1][j],(v[i]+t[i-1][j-w[i]]));

64 | P a g e
Analysis And Design of Algorithms

i=n;

k=W;

while(i>0 && k>0)

if(t[i][k]!=t[i-1][k])

printf("Selected item is %d and weight is %d\n",i,w[i]);

i--;

k=k-w[i];

else

i--;

return t[n][W];

void main()

inti,j;

int v[20],w[20],W,n,pro;

clrscr();

printf("Enter number of total Items:");

scanf("%d",&n);

printf("Enter the capacity of knapsack:");

scanf("%d",&W);

printf("Enter weight and profit according to descending order of ratio\n");

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

printf("Enter w[%d]:",i);

65 | P a g e
Analysis And Design of Algorithms

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

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

printf("Enter v[%d]:",i);

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

pro=dynamic_knap(n,W,w,v);

printf("Maximum profit=%d",pro);

getch();

Output
Enter number of total Items:4

Enter the capacity of knapsack:5

Enter weight and profit according to descending order of ratio

Enter w[1]:2

Enter w[2]:3

Enter w[3]:4

Enter w[4]:5

Enter v[1]:3

Enter v[2]:4

Enter v[3]:5

Enter v[4]:6

Selected item is 2 and weight is 3

Selected item is 1 and weight is 2

Maximum profit=7

66 | P a g e
Analysis And Design of Algorithms

22. Write a program to implement to find shortest path using Floyd’s Algorithm using
Dynamic Programming.
//This program is for computing shortest path using Floyd's algorithm

#include<stdio.h>

#include<conio.h>

int min(int a,int b)

if(a<b)return(a);

else

return(b);

void fsp(int wt[20][20],int n)

int d[10][20][20],i,j,k;

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

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

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

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

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

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

d[k][i][j]=min(d[k-1][i][j],d[k-1][i][k]+d[k-1][k][j]);

67 | P a g e
Analysis And Design of Algorithms

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

printf("\nd(%d)=\n",k);

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

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

printf("%d\t",d[k][i][j]);

printf("\n");

void main()

int wt[20][20],n,i,j;

clrscr();

printf("Create a graph using adjacency matrix");

printf("\nHow many vertices are there? ");

scanf("%d",&n);

printf("\nEnter the elements");

printf("\nEnter 999 as infinity value");

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

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

printf("\nwt[%d][%d]= ",i,j);

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

68 | P a g e
Analysis And Design of Algorithms

printf("\n Computing Shortest path\n");

fsp(wt,n);

getch();

Output
Create a graph using adjacency matrix

How many vertices are there? 5

Enter the elements

Enter 999 as infinity value

wt[1][1]= 0
wt[1][2]= 8
wt[1][3]= 7
wt[1][4]= -2
wt[1][5]= 999

wt[2][1]= 999
wt[2][2]= 0
wt[2][3]= 4
wt[2][4]= 999
wt[2][5]= 1

wt[3][1]= 999
wt[3][2]= 999
wt[3][3]= 0
wt[3][4]= 999
wt[3][5]= 1

wt[4][1]= 999
wt[4][2]= 999
wt[4][3]= 3
wt[4][4]= 0
wt[4][5]= -5

wt[5][1]= 6
wt[5][2]= 3
wt[5][3]= 999
wt[5][4]= 999
wt[5][5]= 0
Computing Shortest path
d(0)=
0 8 7 -2 999

69 | P a g e
Analysis And Design of Algorithms

999 0 4 999 1
999 999 0 999 1
999 999 3 0 -5
6 3 999 999 0

d(1)=
0 8 7 -2 999
999 0 4 997 1
999 999 0 997 1
999 999 3 0 -5
6 3 13 4 0

d(2)=
0 8 7 -2 9
999 0 4 997 1
999 999 0 997 1
999 999 3 0 -5
6 3 7 4 0

d(3)=
0 8 7 -2 8
999 0 4 997 1
999 999 0 997 1
999 999 3 0 -5
6 3 7 4 0

d(4)=
0 8 1 -2 -7
999 0 4 997 1
999 999 0 997 1
999 999 3 0 -5
6 3 7 4 -1

d(5)=
-1 -4 0 -3 -8
7 0 4 5 0
7 4 0 5 0
1 -2 2 -1 -6
5 2 6 3 -2

70 | P a g e
Analysis And Design of Algorithms

23. Write a program to implement Matrix Chain Multiplication using Dynamic


Programming.
#include<stdio.h>

#include<conio.h>

#define INFINITE 999

int m[20][20],n;

void display(int s[20][20],int i,int j)

if(i==j)

printf("A%d",i);

else

printf("(");

display(s,i,s[i][j]);

display(s,s[i][j]+1,j);

printf(")");

int matrix_chain(int p[10])

inti,j,l,k,q,s[20][20];

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;

71 | P a g e
Analysis And Design of Algorithms

m[i][j]=INFINITE;

for(k=i;k<j;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;

printf("\nm[%d][%d]=%d",i,j,m[i][j]);

printf("\n");

display(s,1,n);

return(m[1][n]);

void main()

int p[20],i,j,c;

clrscr();

printf("Enter total number of Matrices you want to multiply:");

scanf("%d",&n);

printf("Enter the dimensions of each matrix\n");

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

printf("p[%d]:",i);

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

72 | P a g e
Analysis And Design of Algorithms

c=matrix_chain(p);

printf("\nThe optimal cost=%d",c);

getch();

Output
Enter total number of Matrices you want to multiply:4

Enter the dimensions of each matrix

p[0]=5

p[1]=4

p[2]=6

p[3]=2

p[4]=7

m[1][2]=120

m[2][3]=48

m[3][4]=84

m[1][3]=88

m[2][4]=104

m[1][4]=158

((A1(A2A3))A4)

The optimal cost=158

73 | P a g e
Analysis And Design of Algorithms

24. Write a program to implement Longest Common Subsequence using Dynamic


Programming.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

intm,n,i,j,c[20][20],k;

char d[20][20],lc[20];

char a[20]="klokmknklok";

char b[20]="xkllknkllknyy";

clrscr();

m=strlen(a);

n=strlen(b);

//================================

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

c[i][-1]=0;

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

c[-1][j]=0;

//=================================

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

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

if(a[i]==b[j])

74 | P a g e
Analysis And Design of Algorithms

c[i][j]=c[i-1][j-1]+1;

d[i][j]='!';

else if(c[i-1][j]>=c[i][j-1])

c[i][j]=c[i-i][j];

d[i][j]='|';

else

c[i][j]=c[i][j-1];

d[i][j]='-';

i=m-1;

j=n-1;

k=0;

while(i>=0 || j>=0)

if(d[i][j]=='!')

lc[k]=a[i];

i--;

j--;

k++;

else if(d[i][j]=='|')

75 | P a g e
Analysis And Design of Algorithms

i--;

else

j--;

lc[k]='\0';

printf("Longest Common Subsequence:");

for(i=k-1;i>=0;i--)

printf("%c",lc[i]);

getch();

Output
Longest Common Subsequence:klknklk

76 | P a g e
Analysis And Design of Algorithms

25. Write a program to implement Breadth First Search


#include<stdio.h>
#include<conio.h>
intn,q[20];
intr,f;
int g[20][20];
int visited[20];
voidbfs(int v)
{
int u;
r=f=-1;
visited[v]=1;
q[++r]=v;
while(r!=f)
{
v=q[++f];
printf("%d\n",v);
for(u=0;u<n;u++)
{
if(visited[u]==0 && g[v][u]==1)
{
q[++r]=u;
visited[u]=1;
}
}
}
}
void main()
{
inti,j;
int v1,v2,v;
charans='y';
clrscr();
printf("Enter total number of Vertices in the given graph:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
g[i][j]=0;
}
}
for(i=0;i<n;i++)
visited[i]=0;
printf("\nEnter the values of edges:\n");
do
{
printf("\nEnter v1:");
scanf("%d",&v1);
printf("Enter v2:");
scanf("%d",&v2);
if(v1>=n || v2>=n)
printf("Invalid vertex\n");
else

77 | P a g e
Analysis And Design of Algorithms

{
g[v1][v2]=1;
g[v2][v1]=1;
}
printf("Do you want to add more vertices:");
ans=getche();
}while(ans=='y');
printf("\nEnter the vertex from which u want to traverse:");
scanf("%d",&v);
bfs(v);
getch();
}

Output
Enter total number of Vertices in the given graph:4

Enter the values of edges:

Enter v1:0

Enter v2:1

Do you want to add more vertices(y/n):y

Enter v1:0

Enter v2:2

Do you want to add more vertices(y/n):y

Enter v1:1

Enter v2:3

Do you want to add more vertices(y/n):y

Enter v1:2

Enter v2:3

Do you want to add more vertices(y/n):n

Enter the vertex from which u want to traverse:0

78 | P a g e
Analysis And Design of Algorithms

26. Write a program to implement Depth First Search

#include<stdio.h>

#include<conio.h>

intn,q[20];

intr,f;

int g[20][20];

int visited[20];

voiddfs(int v)

int i;

visited[v]=1;

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

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

if(visited[i]==0 && g[v][i]==1)

dfs(i);

void main()

int i,j;

int v1,v2,v;

char ans='y';

clrscr();

printf("Enter total number of Vertices in the given graph:");

scanf("%d",&n);

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

79 | P a g e
Analysis And Design of Algorithms

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

g[i][j]=0;

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

visited[i]=0;

printf("Enter the values of edges:\n");

do

printf("\nEnter v1:");

scanf("%d",&v1);

printf("Enter v2:");

scanf("%d",&v2);

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

printf("Invalid Vertex Value\n");

else

g[v1][v2]=1;

g[v2][v1]=1;

printf("Do you want to add more vertices:");

ans=getche();

}while(ans=='y');

printf("\nEnter the vertex from which u want to traverse:");

scanf("%d",&v);

dfs(v);

getch();

80 | P a g e
Analysis And Design of Algorithms

Output
Enter total number of Vertices in the given graph:4

Enter the values of edges:

Enter v1:0

Enter v2:1

Do you want to add more vertices(y/n):y

Enter v1:0

Enter v2:2

Do you want to add more vertices(y/n):y

Enter v1:1

Enter v2:3

Do you want to add more vertices(y/n):y

Enter v1:2

Enter v2:3

Do you want to add more vertices(y/n):n

Enter the vertex from which u want to traverse:0

81 | P a g e
Analysis And Design of Algorithms

27. Write a program to implement Knapsack problem using backtracking.

#include<stdio.h>

#include<conio.h>

#include<math.h>

int w[10],p[10],m,n,y[10],x[10];

int fp=-1,fw;

int bound(int cp,int cw,int k)

int b,c,i;

b=cp;

c=cw;

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

c=c+w[i];

if(c<m)

b=b+p[i];

else

return(b+(1-(c-m)/w[i])*p[i]);

return(b);

int bknap(int k,int cp,int cw)

int j;

if(cw+w[k]<=m)

y[k]=1;

if(k<n)

bknap(k+1,cp+p[k],cw+w[k]);

if((cp+p[k]>fp) && (k==n))

82 | P a g e
Analysis And Design of Algorithms

fp=cp+p[k];

fw=cw+w[k];

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

x[j]=y[j];

if(bound(cp,cw,k)>=fp)

y[k]=0;

if(k<n)

bknap(k+1,cp,cw);

if((cp>fp) && (k==n))

fp=cp;

fw=cw;

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

x[j]=y[j];

void main()

int i,j;

clrscr();

printf("Enter N:");

scanf("%d",&n);

printf("Enter the capacity of knapsack:");

scanf("%d",&m);

printf("Enter weight and profit according to descending order of ratio\n");

83 | P a g e
Analysis And Design of Algorithms

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

printf("Enter w[%d]:",i);

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

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

printf("Enter p[%d]:",i);

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

bknap(1,0,0);

printf("Following Items are selected from Knapsack...");

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

if(x[i]==1)

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

printf("\nWeight=%d",fw);

printf("\nProfit=%d",fp);

getch();

84 | P a g e
Analysis And Design of Algorithms

Output
Enter N:8

Enter the capacity of knapsack:110

Enter weight and profit according to descending order of ratio

Enter w[1]:1

Enter w[2]:11

Enter w[3]:21

Enter w[4]:23

Enter w[5]:33

Enter w[6]:43

Enter w[7]:45

Enter w[8]:55

Enter p[1]:11

Enter p[2]:21

Enter p[3]:31

Enter p[4]:33

Enter p[5]:43

Enter p[6]:53

Enter p[7]:55

Enter p[8]:65

Following Items are selected for knapsack…

Item 1

Item 2

Item 3

Item 5

Item 6

Weight=109

Profit=159

85 | P a g e
Analysis And Design of Algorithms

28. Write a program to implement N Queen Problem using Backtracking.

#include<stdio.h>
#include<conio.h>
#include<math.h>
int x[25];
int c=0;
int p(int k,int i)
{
int j;
for(j=1;j<=k-1;j++)
{
if((x[j]==i) || (abs(x[j]-i)==abs(j-k)))
return(0);
}
return(1);
}
void nq(int k,int n)
{
int i,j;
for(i=1;i<=n;i++)
{
if(p(k,i))
{
x[k]=i;
if(k==n)
{
printf("\nSolution Vector:");
for(j=1;j<=n;j++)
printf("%d ",x[j]);
c++;
}
else
nq(k+1,n);
}
}
}
void main()
{
int n,i,j;
clrscr();
printf("Enter N:");
scanf("%d",&n);
nq(1,n);
printf("\n\nTotal Solution Vectors are %d",c);
getch();
}

Output
Enter N:4
Solution vector:2 4 1 3
Solution vector:3 1 4 2

Total Solution Vectors are 2

86 | P a g e
Analysis And Design of Algorithms

29. Write a program to implement Naïve String Algorithm using String Matching
Algorithm.

#include<stdio.h>

#include<conio.h>

#include<string.h>

void naive(char t[100],char p[100])

int m,n,i,j,k;

char s[100];

n=strlen(t);

m=strlen(p);

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

j=0;

while((j<m)&&(p[j]==t[i+j]))

j=j+1;

if(j==m)

printf("Pattern Finding with shift %d",i);

void main()

char t[100],p[100];

clrscr();

printf("Enter the text:-");

gets(t);

87 | P a g e
Analysis And Design of Algorithms

printf("Enter the Pattern:-");

gets(p);

naive(t,p);

getch();

Output
Enter the text:-Sunny and Pratik

Enter the Pattern:-Pratik

Pattern Finding with shift 10

88 | P a g e
Analysis And Design of Algorithms

30. Write a program to implement Rabin Karp using String Matching Algorithm.

//Rabin-Karp String Matching Algorithm

//RabinKarpMatch(T,P,d,q)

//Assume T and P consist only a..z and A..Z , radix d, prime q,

//This algorithm matches whether P is a substring of T and returnthe starting index of the firstoccurence of
//P in T. Also n is length(T) and m islength(P).

//Complexity Worst Case : O((n-m+1)*m) Best Case : O(n+m)

#include<stdio.h>

#include<conio.h>

#include<math.h>

#include<string.h>

//Macro Defined

#define tonum(c) (c >= 'A' && c <= 'Z' ? c - 'A' : c - 'a'+26) //converts alphabets to //numbers

int mod(inta,intp,int m)

intsqr;

if(p==0)

return(1);

sqr=mod(a,p/2,m)%m;

sqr=(sqr*sqr)%m;

if(p & 1)

return((a%m)*sqr)%m;

else

return(sqr);

int rabin_karp_matcher(char T[100],char P[100],int d,int q)

int m,n,h,p=0,t=0,i,f,j;

n=strlen(T);

89 | P a g e
Analysis And Design of Algorithms

m=strlen(P);

h=mod(d,m-1,q);

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

p=(d*p+tonum(P[i]))%q;

t=(d*t+tonum(T[i]))%q;

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

if(p==t)

f=1;

for(j=0;i<m;j++)

if(P[j]!=T[i+j])

f=0;

break;

if(f)

return(i);

else

if(i<n-m)

t=(d*(t-((tonum(T[i])*h)%q))+tonum(T[i+m]))%q;

return(-1);

void main()

90 | P a g e
Analysis And Design of Algorithms

char t[100],p[100];

intans,d,q;

clrscr();

printf("Enter the text:-");

gets(t);

printf("Enter the occurrence Pattern:-");

gets(p);

printf("Enter the base(radix) for the text:");

scanf("%d",&d);

printf("Enter the value of (prime) q for hash function:");

scanf("%d",&q);

ans=rabin_karp_matcher(t,p,d,q);

if(ans==-1)

printf("\nNot Found !"); // ans =-1 means Unsuccessful search

else

printf("\nFound at Pos. %d",ans+1); //Successful search

getch();

Output
Enter the text:-3141592653589793

Enter the occurrence Pattern:26

Enter the base(radix) for the text:11

Enter the value of (prime) q for hash function:11

Found at pos. 7

91 | P a g e

You might also like