Design and Analysis of Algorithm Practicals
Design and Analysis of Algorithm Practicals
Design and Analysis of Algorithm Practicals
PRACTICAL-1
Aim: Implement and analyze algorithms given below.
1.1 Factorial (Iterative and Recursive)
1.2 Fibonacci Series(Iterative and Recursive)
1.3 Matrix Addition and Matrix Multiplication(Iterative)
1.4 Recursive Linear Search and Binary Search (Comparative Study)
Iterative Factorial :
Theory:
The factorial of a positive number n is given by:
Factorial of n = 1*2*…*n
The factorial of a negative number doesn't exist. And, the factorial of 0 is
1, 0! = 1.
Algorithm:
1. Start
2. Read the number n
3. [Initialize]
i=1, fact=1
4. Repeat step 4 through 6 until i=n
5. Fact=fact*i
6. I=i+1
7. Print fact
8. Stop
Code:
#include<stdio.h>
int main(){
int i=1,f=1,num,c=0;
1|Page
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
while(i<=num){
f=f*i;
i++;
c=c+2;
}
Graph:
Sr. No. Input No. No. of Count
1 1 6
2 2 7
3 3 8
4 4 9
5 5 10
2|Page
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
12
Iterative Factorial
10 10
f(x) = x + 5
9
8
8
No. of count 7
6 6
Linear ()
4
0
0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5
Input numbers
Recursive Factorial :
Code:
#include<stdio.h>
int fact(int num);
int c=0;
int main(){
int num;
c++;
printf("Enter a number: ");
c++;
scanf("%d",&num);
c++;
printf("Factorial of %d is: %d",num,fact(num));
c++;
printf("\nCounter : %d",c);
return 0;
}
int fact(int n){
if(n>=1){
c++;
return n*fact(n-1);
c++;
3|Page
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
}
else{
c++;
return 1;
}
}
Output:
Graph:
Size of Input No. of count
1 5 10
2 10 15
3 15 20
4 20 25
5 25 30
Recursive Factorial
35
30 30
f(x) = x + 5
25 25
No. of count
20 20
15 15 No. of count
10 10
Linear (No. of count)
5
0
0 5 10 15 20 25 30
Size of Input
4|Page
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Theory:
The Fibonacci sequence is a series where the next term is the sum of pervious
two terms. The first two terms of the Fibonacci sequence is 0 followed by 1.
1. declare f1,f2,fib,loop
2. set f2 to 0
3. set f2 to 0
4. display f1,f2
5. for loop 1 to n
6. fib=f1+f2
7. f1=f2
8. f2=fib
9. end for loop
10. display fib
Code:
#include<stdio.h>
int main(){
int n,first=0,second=1,next,i,c=0;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
c=c+5;
for (i=0;i<n;i++){
c=c+2;
if ( i<= 1 ){
next = i;
c=c+2;
}
else{
next = first + second;
first = second;
second = next;
c=c+3;
}
printf(" %d ",next);
5|Page
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
}
printf("\nCOunter: %d",c);
return 0;
}
Output:
Graph:
Sr. No No Of Inputs Counts
1 5 27
2 10 62
3 15 97
4 20 132
5 25 167
180
160 167
f(x) = 7 x − 8
140
132
120
C o u n ts
100 97
80 Linear ()
60 62
40
20 27
0
0 5 10 15 20 25 30
No Of Inputs
fibo(n,a,b);
printf("\nCounter:%d",c);
return 0;
}
int fibo(int n,int a,int b){
a=a+b;
c++;
printf("%d ",a);
c++;
if(n-2>0){
c++;
return fibo(n-1,b,a);
c++;
}
Output:
Graph:
7|Page
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
f(x) = 0
Recursive Fibonacci series :
12
10
Linear ()
6
0
0 2 4 6 8 10 12
8|Page
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Matrix Addition :
Theory:
This program asks user to enter the size of the matrix (rows and column) then,
it asks the user to enter the elements of two matrices and finally it adds two
matrix and displays the result.
Algorithm:
1. Start
2. Read: m and n
3. Read: Take inputs for Matrix A[1:m, 1:n] and Matrix B[1:m, 1:n]
4. Repeat for i := 1 to m by 1:
Repeat for j := 1 to n by 1:
C[i, j] := A[i, j] + B[i, j]
[End of inner for loop]
[End of outer for loop]
5. Print: Matrix C
6. Exit.
Code:
#include<stdio.h>
#include<conio.h>
int main(){
int a[10][10],b[10][10],c[10][10],d[10][10],i,j,k,c1=0,c2=0,c3=0,n;
c1++;
printf("Enter Size of Matrix:");
scanf("%d",&n);
printf("Enter Matrix A of size %d:\n",n);
c1++;
for(i=0;i<n;i++){
c2=c2+3;
for(j=0;j<n;j++){
c3=c3+3;
scanf("%d",&a[i][j]);
c3++;
}
}
printf("Enter Matrix B of size %d:\n",n);
c1++;
for(i=0;i<n;i++){
c2=c2+3;
for(j=0;j<n;j++){
c3=c3+3;
scanf("%d",&b[i][j]);
c3++;
9|Page
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
}
}
printf("Addition Matrix:\n");
c1++;
for(i=0;i<n;i++){
c2=c2+3;
for(j=0;j<n;j++){
c3=c3+3;
c[i][j]=a[i][j]+b[i][j];
c3++;
}
}
for(i=0;i<n;i++){
c2=c2+3;
for(j=0;j<n;j++){
c3=c3+3;
printf(" %d ",c[i][j]);
c3++;
}
printf("\n");
c1++;
}
printf("Counter for addition=%d",c1+c2+c3);
}
Output:
Graph:
10 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Matrix Addition
600
520
500 f(x) = 12 x² + 37 x + 35
N o . o f co u n t
400
375
0
0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5
Size of matrix
Matrix multiplication :
Theory:
This program asks user to enter two matrices and this program multiplies these
two matrix and displays it. If you don't know matrix multiplication, visit this
page to learn, how two matrix can be multiplied.
Algorithm:
1. Start.
2. Read: m, n, p and q
3. Read: Inputs for Matrices A[1:m, 1:n] and B[1:p, 1:q].
4. If n ≠ p then:
Print: Multiplication is not possible.
Else:
Repeat for i := 1 to m by 1:
Repeat for j := 1 to q by 1:
C[i, j] := 0 [Initializing]
Repeat k := 1 to n by 1
C[i, j] := C[i, j] + A[i, k] x B[k, j]
[End of for loop]
[End of for loop]
[End of for loop]
[End of If structure]
5. Print: C[1:m, 1:q]
6. Exit.
11 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Code:
#include<stdio.h>
#include<conio.h>
void main(){
int a[3][3],b[3][3],c[3][3],d[3][3],i,j,k,c1=0,c2=0,c3=0,n;
c1++;
printf("Enter Size of Matrix:");
c1++;
scanf("%d",&n);
c1++;
printf("Enter Matrix A of size %d:\n",n);
c1++;
for(i=0;i<n;i++){
c2=c2+3;
for(j=0;j<n;j++){
c3=c3+3;
scanf("%d",&a[i][j]);
c3++;
}
}
printf("Enter Matrix B of size %d:\n",n);
c1++;
for(i=0;i<n;i++){
c2=c2+3;
for(j=0;j<n;j++){
c3=c3+3;
scanf("%d",&b[i][j]);
c3++;
}
}
for(i=0;i<n;i++){
12 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
c2=c2+3;
for(j=0;j<n;j++){
c3=c3+3;
d[i][j]=0;
c3++;
}
}
for(i=0; i<n; ++i){
c1=c1+3;
for(j=0;j<n; ++j){
c2=c2+3;
for(k=0; k<n; ++k){
c3=c3+3;
d[i][j]+=a[i][k]*b[k][j];
c3++;
}
}
}
printf("\nMultipication Matrix:\n");
c1++;
for(i=0; i<n; ++i){
c2=c2+3;
for(j=0; j<n; ++j){
c3=c3+3;
printf(" %d ",d[i][j]);
c3++;
}
printf("\n");
c1++;
}
printf("Counter=%d",c1+c2+c3);
13 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
}
Output:
Graph:
Matrix multiplication
2000
1800
1721
1600 f(x) = 4 x³ + 32 x² + 73 x + 56
1400
1200
No.of count
Size of matrix
14 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
15 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
}
}
else{
c++;
printf("Element Not Found.");
}
}
Output:
Graph:
50
38
40 30
30 24
20 10 10 10 10
10
0 f(x) = 10
4 6 8 10 12 14 16 18 20 22
Size of List
16 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Code:
#include<stdio.h>
int binarys(int m,int n,int *pt,int k);
int count=0;
int main(){
int *data;
int x,l,n,i,ans;
printf("\nEnter The Limit:");
scanf("%d",&n);
data = (int*) malloc(n*sizeof(int));
printf("\nEnter The Data:");
for(i=0;i<n;i++){
scanf("%d",(data+i));
}
printf("\nEnter The Element To Be Searched:");
scanf("%d",&x);
ans=binarys(0,n-1,data,x);
if(ans==-1){
printf("Element Not Found.");
}
else{
printf("\nElement Is Found At The Index %d. ",ans+1);
}
printf("\nCount : %d",count+9);
}
int binarys(int m,int n,int *pt,int k){
int mid;
if(m>n){
count++;
17 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
return -1;
}
count+=2;
mid=(m+n)/2;
if(k<*(pt+mid)){
count+=2;
n=mid-1;
return binarys(m,n,pt,k);
}
else if(k>*(pt+mid)){
count+=4;
m=mid+1;
return binarys(m,n,pt,k);
}
else if(k==*(pt+mid)){
count+=4;
return mid;
}
}
Output:
Graph:
Binary Search
Size of list Best Case Average List Worst Case
5 15 25 28
10 15 30 33
15 15 35 41
20 15 40 49
18 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
- Best case :
16 15 15 15 15
f(x) = 15
14
12
10
8
Linear ()
6
0
4 6 8 10 12 14 16 18 20 22
Binary Search
60
49
50
f(x) = 14.64 ln(x) + 2.55 41 40
40 35
f(x) = 10.52 ln(x) + 7.2 33
30
28
Count
30 25
20
10
0
4 6 8 10 12 14 16 18 20 22
Size of List
19 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Time complexity:
Conclusion: From this practical, we have learnt about iterative and recursive approach to
find factorial of any number and fibonacci series. We have also learnt various search
techniques like linear search and binary search and an iterative approach for matrix addition
and matrix multiplication.
20 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
PRACTICAL 2
Aim: Implement and analyze algorithms given below (compare them).
2.1 Bubble Sort
2.2 Selection Sort
2.3 Insertion Sort
3. E ← 0
4. Repeat for i=1,2,..,last-1
If k[i] > k[i+1]
then k[i] ↔ k[i+1]
E ← E+1
5. If E=0
then return
else
last ← last-1
6. Return number of passes
Code:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
int main(){
int i,j,k,temp,n,*p,e,c=0,swap=0,comp=0;
printf("Enter n : ");
scanf("%d",&n);
printf("\nEnter an array of %d integers :\n",n);
p=(int*)malloc(sizeof(n));
for(i=0;i<n;i++){
scanf("%d",p+i);
}c++;
for(i=0;i<n;i++){
c=c+2;
e=0;
c++;
c++;
for(j=0;j<n-i-1;j++){
c=c+2;
comp=comp+1;
if(*(p+j)>*(p+j+1)){
c++;
temp=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=temp;
e=e+1;
swap=swap+1;
c=c+4;
}
}
22 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
- Best case :
- Worst case :
23 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
- Average case :
Graph:
Bubble Sort
Sr. No No Of Inputs Best Case Average Case Worst Case
Counts
1 5 14 92 73
2 10 24 357 103
3 15 34 797 133
4 20 44 1412 163
5 25 54 2202 193
- Best case :
30 24
Linear ()
20 14
10
0
0 5 10 15 20 25 30
No.of input
- Worst case :
24 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
1500 1412
Count
1000 Polynomial ()
797
500
357
92
0
0 5 10 15 20 25 30
No. of Input
- Average case :
800 805
Polynomial ()
600
400 400
200 158
73
0
0 5 10 15 20 25 30
No. of Input
25 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Code:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
26 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
int main(){
int n,*p,i,j,k,min,temp,c,swap=0,comp=0,ct=0;
printf("Enter n :");
scanf("%d",&n);
printf("\nEnter an array of %d integers:\n",n);
p=(int*)malloc(sizeof(n));
for(i=0;i<n;i++){
scanf("%d",p+i);
}
ct++;
for(i=0;i<n;i++){
ct=ct+2;
min=*(p+i);
ct++;
c=i;
ct++;
for(j=i+1;j<n;j++){
ct=ct+2;
if(*(p+j)<=min){
ct++;
comp++;
min=*(p+j);
ct++;
c=j;
}
}
if(c!=i){
temp=*(p+c);
*(p+c)=*(p+i);
*(p+i)=temp;
ct=ct+3;
swap++;
}
printf("\nAfter Pass %d:",i+1);
for(k=0;k<n;k++)
printf(" %d ",*(p+k));
}
printf("\nSelection : \n");
for(i=0;i<n;i++){
printf("%d ",*(p+i));
}
printf("\nCounter value:%d \nSwapping Value:%d \nNo. of Comparision:
%d",ct,swap,comp);
return 0;
}
27 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
- Best case :
- Worst case :
- Average case :
28 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Graph:
Selection Sort
Sr. No No Of Inputs Best Case Average Case Worst Case
Counts
1 5 41 59 53
2 10 131 196 180
3 15 271 404 351
4 20 461 691 595
5 25 701 1049 923
- Best case :
400
Polynomial ()
300
271
200
131
100
41
0
0 5 10 15 20 25 30
No. of Input
- Worst case :
800
691
Count
600
Polynomial ()
400 404
200 196
59
0
0 5 10 15 20 25 30
No. of Input
500
Polynomial ()
400
351
300
200 180
100
53
0
0 5 10 15 20 25 30
No. of Input
30 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Example:
Algorithm:
1. For j←2 to n
do key ← A[j]
2. i ← j-1
3. while i>0 & A[i]>key
do A[i+1] ← A[i]
i←i-1
4. A[i+1]←key
31 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Code:
#include<stdio.h>
void main(){
int *data, i, j, n, insert, pos, k, swap=0, comp=0;
printf("Enter The Range:");
scanf("%d",&n);
data = (int*) malloc(sizeof(int)*n);
printf("\n");
for(i=0;i<n;i++){
printf("Enter element %d : ",i+1);
scanf("%d",(data + i));
}
for(i=1;i<n;i++){
insert=*(data + i);
pos=i;
comp++;
while(pos>0 && *(data+pos-1)>insert){
*(data + pos)=*(data+pos-1);
swap++;
pos--;
}
*(data + pos)=insert;
printf("\n PASS %d : ",i+1);
for(k=0; k<n; k++) {
printf(" %d",*(data + k));
}
printf("\n\nSorted Array:");
for(i=0;i<n;i++){
printf("%d ",*(data + i));
printf("\nNo. of Swaps : %d", swap);
printf("\nNo. of Comparisons : %d", comp);
}
Output:
- Best case :
32 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
- Worst case :
- Average case :
Graph:
Insertion Sort
Sr. No No Of Inputs Best Case Average Case Worst Case
Counts
1 5 34 92 73
2 10 50 357 103
3 15 74 797 133
33 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
- Best case :
40
34 Linear ()
30
20
10
0
4 5 6 7 8 9 10 11
No. of Inputs
- Worst case :
100
92
80 Polynomial ()
60 54
40
20
0
4 5 6 7 8 9 10 11
No. of Inputs
34 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
- Average case :
120 116
f(x) = 0.8 x² + 2.4 x + 12
100
80
C o u n ts
68
60 Polynomial ()
40 44
20
0
4 5 6 7 8 9 10 11
No. of Inputs
Time Complexity:
Conclusion: From this practical, we have learnt about various sorting algorithms and
there complexities in various cases and comparisons between them.
35 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
PRACTICAL – 3
Theory:
Example:
36 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Algorithm:
- Simple Merge :
SIMPLE_MERGE_SORT(K,FIRST,SECOND,THIRD)
1. [INITIALIZE]
2. [FIND SMALLEST ELEMENT]
I ← FIRST
J ← SECOND
L←0
Repeat While I<SECOND and J≤THIRD
If K[I] ≤ K[J]
Then L ← L+1
Else L ← L+1
TEMP[L] ← K[I]
I ← I+1
TEMP[L] ← K[I]
J ← J+1
3. [COPY THE REMAINING ELEMENTS]
If I≥SECOND
Then Repeat while J≤THIRD
L ← L+1
TEMP[L] ← K[J]
J ← J+1
Else Repeat while I<SECOND
L ← L+1
TEMP[L] ← K[I]
I ← I+1
4. [COPY ELEMENTS]
Repeat for I=1,2…L
K[FIRST-1+I] ← TEMP[I]
5. [FINISHED] Return
Code:
#include<stdio.h>
void divide(int *a, int min, int max, int *tmp);
void merge(int *a, int min, int mid, int max, int *tmp);
int count=0,comp=0;
int x=1;
void main(){
int *a, i, j, n,*tmp;
printf("Enter the size of array : ");
37 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
scanf("%d", &n);
a = (int *) malloc(sizeof(int)*n);
tmp = (int *) malloc(sizeof(int)*n);
for(i=0;i<n;i++){
printf("Enter element %d : ",i+1);
scanf("%d", &a[i]);
}
count++;
divide(a,0,n-1,tmp);
printf("\n\nSorted array is : \n");
for(i=0;i<n;i++){
printf(" %d", tmp[i]);
}
printf("\n\nNo. of Counts: %d", count);
printf("\nNo. of Comparisons: %d" ,comp);
}
void divide(int *a, int min, int max, int *tmp){
int mid;
if(min!=max){
mid=((min + max)/2);
divide(a, min, mid, tmp);
divide(a, mid+1,max,tmp);
merge(a, min, mid, max, tmp);
count+=4;
}
count++;
}
void merge(int *a, int min, int mid, int max, int *tmp){
int i=min, j=mid+1, k=min;
count++;
while(i<=mid && j<=max){
count++; comp++;
if(a[i]<a[j]) { tmp[k]=a[i]; i++; }
else { tmp[k]=a[j]; j++; }
k++;
count+=4;
}
count++;
while(j<=max) { tmp[k]=a[j]; k++; j++; count+=4; }
count++;
while(i<=mid) { tmp[k]=a[i]; k++; i++; count+=4; }
printf("\n AFTER PASS %d : ",x); x++;
for(i=min; i<=max; i++){
count++;
a[i]=tmp[i];
38 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
printf(" %d",a[i]);
}
}
Output:
- Best case :
- Average case :
- Worst case :
39 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Graph:
- Best case :
200
167
Counts
150
Logarithmic ()
100 105
50
0
4 5 6 7 8 9 10 11
No Of Inputs
- Average case :
40 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
3 10 275 22
200
169
Counts
150
Logarithmic ()
100 106
50
0
4 5 6 7 8 9 10 11
No Of Inputs
- Worst case :
200
168
Counts
150
Logarithmic ()
100 105
50
0
4 5 6 7 8 9 10 11
No Of Inputs
41 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
42 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Theory:
Example:
Input: 65 70 75 80 85 60 55 50 45
P: 65 i
Pass 1: 65 70 75 80 85 60 55 50 45
i j swap (A[i], A[j])
(i) 65 45 75 80 85 60 55 50 70
i j swap (A[i], A[j])
(ii) 65 45 50 80 85 60 55 75 70
i j swap (A[i], A[j])
(iii) 65 45 50 55 85 60 80 75 70
i j swap (A[i], A[j])
(iv) 65 45 50 55 60 85 80 75 70
j i if (i>=j) break 60 45 50 55 65 85 80 75 70 swap (A[left],
A[j])
Result of Pass 1: 3 60 45 50 55 65 85 80 75 70
Pass 2a (left sub-block): 60 45 50 55 (P = 60)
i j
(i) 60 45 50 55
j i if (i>=j) break 55 45 50 60 swap (A[left], A[j])
43 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Algorithm:
QUICK_SORT(K,LB,UB)
1. [INITIALIZE]
FLAG ← true
2. [PERFORM SORT]
If LB<UB
Then I ← LB
J ← UB+1
KEY ← K[LB]
Repeat while FLAG
I ← I+1
Repeat while K[I]<KEY
I ← I+1
J ← J-1
Repeat while K[J]>KEY
J ← J-1
If I<J
Then K[I] ↔ K[J]
Else FLAG ← false
K[LB] ↔ K[J]
Call QUICK_SORT(K,LB,J-1)
Call QUICK_SORT(K,J+1,UB)
3. [FINISHED]
Return
Code:
#include<stdio.h>
int count=0, swap=0, comp=0;
void main(){
int *a, i, j, n, start ,end;
printf("Enter The Range:");
scanf("%d",&n);
a = (int *) malloc(sizeof(int)*n);
printf("\nEnter The Elements:");
for(i=0;i<n;i++){
scanf("%d", (a + i));
}
start=0;
end=n-1;
printf("\n Sublists: \n");
quicksort(a, start, end);
printf("\nNo. of Counts: %d", count);
printf("\nNo. of Swaps: %d", swap);
44 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
45 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
- Best case :
- Average case :
46 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
- Worst case :
Graph:
- Best case :
Quick Sort (Best case)
Sr No. No Of Inputs Count Swap Comparisons
1 5 74 3 3
2 7 78 3 3
3 10 162 7 7
100
74 78 Logarithmic ()
80
Polynomial ()
60
40
20
0
4 5 6 7 8 9 10 11
No Of Inputs
- Average case :
86
80 Logarithmic ()
60
40
20
0
4 5 6 7 8 9 10 11
No Of Inputs
- Worst case:
48 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
250 239
f(x) = 0.5 x² + 20.5 x − 16
200
152
Counts
150
Polynomial ()
99
100
50
0
4 5 6 7 8 9 10 11
No Of Inputs
Time complexity:
Conclusion: From this practical, we have learnt time complexity of merge sort
and quick sort and their implementations.
49 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
PRACTICAL – 4
Aim: Greedy Approach
4.1 Making change problem (Implement)
4.2 0/1 and Fractional Knapsack problem (Study/Implement)
4.3 Activity Selection Problem (Study/Implement)
Software Required: CodeBlocks
Hardware Required: NA
Knowledge Required: Basic knowledge of c, c++
Algorithm:
50 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Code:
#include<stdio.h>
#include<conio.h>
int main(){
int c[50],i,q[50],o,n,m,s=0,w[50];
printf("Enter no. of coins:");
scanf("%d",&n);
printf("Enter coins available:");
for(i=0;i<n;i++){
scanf("%d",&c[i]);
}
printf("Enter quantity of each coin:");
for(i=0;i<n;i++){
scanf("%d",&q[i]);
}
for(i=0;i<n;i++){
w[i]=0;
}
printf("enter amount:");
scanf("%d",&o);
if((o%5)==0){
printf("valid");
i=0;
while(s!=o&&i<=n){
if((o-s)>=c[i]){
s=s+c[i];
w[i]++;
}
else{
i++;
}
}
for(i=0;i<n;i++){
printf("\ncoins of %d is %d",c[i],w[i]);
}
}
else{
printf("\ninvalid amount");
}
}
51 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
- Valid
- Invalid
52 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
0/1 knapsack
Theory:
- The most common problem being solved is the 0-1 knapsack problem, which restricts
the number xi of copies of each kind of item to zero or one. Given a set of n items numbered
from 1 up to n, each with a weight wi and a value vi, along with a maximum weight
capacity W,
Maximize Σ vi xi subject to Σ wi xi ≤ W and xi = {0, 1}
- Here xi represents the number of instances of item i to include in the knapsack.
Informally, the problem is to maximize the sum of the values of the items in the knapsack so
that the sum of the weights is less than or equal to the knapsack's capacity.
Example:
I P W
1 12 3
2 8 2
3 10 3
4 20 4
5 18 1
Total weight=10
Maximum Profit Minimum Weight
I=4 P=20 W=10-4=6 I=5 P=18 W=10-1=9
I=5 P=20+18=38 W=6-1=5 I=2 P=18+8=26 W=9-2=7
I=1 P=38+12=50 W=5-3=2 I=1 P=26+12=38 W=7-3=4
I=2 P=50+8=58 W=2-2=0 I=3 P=38+10=48 W=4-3=1
53 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
54 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
Fractional knapsack
Theory:
- An instance of either the fractional knapsack problems may be specified by the
numerical capacity W of the knapsack, together with a collection of materials, each of which
has two numbers associated with it: the weight wi of material that is available to be selected
and the value per unit weight vi of that material. The goal is to choose an amount xi ≤ wi of
each material, subject to the capacity constraint
Σ xi ≤ W and maximizing total benefit Σ xi.vi
- In the fractional knapsack problem, each of the amounts xi must be either zero or wi
the continuous knapsack problem differs by allowing xi to range continuously from zero
to wi. Some formulations of this problem rescale the variables xi to be in the range from 0 to
1.
Example:
I P W P/W
1 14 3 4.67
2 22 5 4.4
3 10 3 3.33
4 20 4 5
5 18 2 9
Maximum Weight = 10
I=5 P=18 W=10-1=9
I=4 P=18+20=38 W=9-4=5
I=1 P=38+14=42 W=5-3=2
I=2 P=42+((2/5)22)=50.8 W=2-2=0
55 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Algorithm:
1. FOR i =1 to n
2. do x[i] =0
3. weight = 0
4. while i ≤ n & weight < W
5. do i = best remaining item
6. IF weight + w[i] ≤ W
7. then x[i] = 1
8. weight = weight + w[i]
9. Else
10. x[i] = (w - weight) / w[i]
11. weight = W
12. i++
13. return x
Code:
#include<stdio.h>
#include<conio.h>
int main(){
int n,m,i,j;
float p[100],w[100],pw[100],a[100],temp,pv=0,x[100];
printf("enter no. of process:");
scanf("%d",&n);
for(i=0;i<n;i++){
x[i]=0;
}
printf("enter processes:");
for(i=0;i<n;i++){
scanf("%f",&a[i]);
}
printf("enter profit values:");
for(i=0;i<n;i++){
scanf("%f",&p[i]);
}
printf("enter weights:");
for(i=0;i<n;i++){
scanf("%f",&w[i]);
}
printf("\n enter max weight:");
scanf("%d",&m);
for(i=0;i<n;i++){
pw[i]=(p[i]/w[i]);
}
56 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(pw[j]<pw[j+1]){
temp=pw[j];
pw[j]=pw[j+1];
pw[j+1]=temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
}
}
}
for(i=0;i<n;i++){
if(w[i]>m){
pv=pv+(p[i]*(m/w[i]));
x[i]=m/w[i];
break;
}
else{
m=m-w[i];
pv=pv+p[i];
x[i]=1.0;
}
}
printf("\nweight\tprofit\tratio");
for(i=0;i<n;i++){
printf("\n%.2f\t%.2f\t%.2f",w[i],p[i],pw[i]);
}
printf("\n knapsack:");
for(i=0;i<n;i++){
printf("%.2f\n",x[i]);
}
printf("\n\ntotal profit:%f",pv);
return 0;
}
57 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
1 Greedy-Iterative-Activity-Selector(A, s, f):
2 Sort A by finish times stored in f'
3 S = {A[1]}
4 k=1
5 n = A.length
6 for i = 2 to n:
7 if s[i] ≥ f[k]:
8 S = S U {A[i]}
9 k=i
58 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
10 return S
Code:
#include<stdio.h>
int main(){
int n,s[10],f[10],i,a[50],temp,j,k=0;
printf("Enter number of activities::\n");
scanf("%d",&n);
printf("Enter start time and finish time for each activity::\n");
printf("Activity\tStart Time\t Finish Time\n");
for(i=0;i<n;i++){
a[i]=i+1;
printf("A[%d]\t",a[i]);
scanf("%d",&s[i]);
scanf("%d",&f[i]);
}
for(i=n-2;i>=0;i--){
for(j=0;j<=i;j++){
if(f[j]>f[j+1]){
temp=f[j+1];
f[j+1]=f[j];
f[j]=temp;
temp=s[j+1];
s[j+1]=s[j];
s[j]=temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
printf("\nArranging the activity in increasing order of finish time\n\n");
for(i=0;i<n;i++){
printf("A[%d]\t",a[i]);
printf("%d\t",s[i]);
printf("%d\n",f[i]);
}
printf("The final activity schedule is ::\n");
printf("\nA[%d]\t",a[0]);
for(i=1;i<n;i++){
if(s[i]>=f[k]){
printf("A[%d]\t",a[i]);
k=i;
}
}
printf("\n");
59 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
return 0;
}
Output:
Conclusion: From this practical we have learnt about Making change problem,
0/1 and Fractional Knapsack problem and Activity Selection problem.
60 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
PRACTICAL – 5
Aim: Dynamic Programming
5.1 Find binomial Co-efficient using Dynamic Programming (Implement)
5.2 0/1 Knapsack Problem (Implement)
5.3 Matrix Chain Multiplication (Implement)
5.4 Longest Common Subsequence (Implement)
Example:
C(3,2) = 3
1 2
1 1
2 2 1
3 3 3
Algorithm:
1 C(n , k) = C (n-1, k-1) + C (n-1, k) for n > k > 0
2 C(n , 0) = 1,
3 C(n , n) = 1 for n ≥ 0
Code:
#include<stdio.h>
int main(){
int k,n;
printf("Enter n: ");
scanf("%d",&n);
61 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
printf("Enter k: ");
scanf("%d",&k);
printf("C(%d,%d) id %d",n,k,B_C(n,k));
return 0;
}
int B_C(int n,int k){
if(k==0||k==n){
return 1;
}
else{
return B_C(n-1,k-1)+B_C(n-1,k);
}
return 0;
}
Output:
Algorithm:
1 for j from 0 to W do:
2 m[0, j] := 0
3 for i from 1 to n do:
4 for j from 0 to W do:
5 if w[i] > j then:
6 m[i, j] := m[i-1, j]
7 else:
8 m[i, j] := max(m[i-1, j], m[i-1, j-w[i]] + v[i])
Code:
#include<stdio.h>
#include<conio.h>
int sum=0;
int max(int a,int b){
if(a>b)
return a;
else
return b;
}
void knapsack(int m,int n,int w[],int p[]){
int v[100][200],x[10],i,j,count=0;
for(i=0;i<=m;i++)
v[0][i]=0;
for(i=1;i<=n;i++){
for(j=0;j<=m;j++){
if(j>=w[i])
v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
else
v[i][j]=v[i-1][j];
}
}
for(i=1;i<=n;i++)
x[i]=0;
i=n;
j=m;
while(i>0 && j>0){
if(v[i][j]!=v[i-1][j]){
63 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
x[i]=1;
j=j-w[i];
}
i--;
}
printf("\n Items in the KnapSack solution are : \n\n");
printf("\tSr.no \tweight profit\n");
printf(" ----------------------------------------\n");
for (i = 1; i <= n; i++)
if (x[i])
printf("\t %d \t %d \t %d\n", ++count, w[i], p[i]);
printf("\n The knapsack solution : ");
for(i=1;i<=n;i++){
if(x[i]==1){
printf("1 ",i);
sum=sum+p[i];
}
else
printf("0 ",i);
}
printf("\n\n Total profit = %d",sum);
}
void main()
{
int w[10],p[10],i,m,n;
printf("\n Enter the number of items : ");
scanf("%d",&n);
printf("\n Enter the weight : ");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
printf("\n Enter the profits for items : ");
for(i=1;i<=n;i++)
scanf("%d",&p[i]);
printf("\n Enter the capacity of knapsack : ");
scanf("%d",&m);
knapsack(m,n,w,p);
getch();
}
64 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output :
Example:
Dimensions: 5 10 6 5 3 2
1 2 3 4 5
1 0 300/1 450/2 420/1 310/1
2 -1 0 300/2 270/2 210/2
3 -1 -1 0 90/3 90/3
4 -1 -1 -1 0 30/4
5 -1 -1 -1 -1 0
65 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Algorithm:
Code:
#include<stdio.h>
#define max_int 10000
int s[10][10];
void matrix(int p[], int n){
int l,i, j,k, temp;
int m[n][n];
for(i=0; i<n; i++){
for(j=0; j<n; j++){
m[i][j] = 0;
s[i][j] = 0;
}
}
for(l=2; l<n; l++){
for(i=1; i<n-l+1; i++){
j = i+l-1;
m[i][j] = max_int;
for(k=i; k<j; k++){
temp = m[i][k] + m[k+1][j] + p[i-1] * p[k] * p[j];
if(temp < m[i][j]){
m[i][j] = temp;
s[i][j] = k;
}
}
}
}
printf("\n Value Matrix:\n\n");
for(i=1; i<n; i++){
66 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
printf("\t");
for(k=1; k<n; k++){
printf("%d ", m[i][k]);
}
printf("\n");
}
printf("\n K values:\n\n");
for(i=1; i<n; i++){
printf("\t");
for(k=1; k<n; k++){
printf("%d ", s[i][k]);
}
printf("\n");
}
}
void solution(int i,int j){
if (i == j)
printf(" A%d",i);
else{
printf(" (");
solution(i, s[i][j]);
solution(s[i][j] + 1, j);
printf(" )");
}
}
int main(){
int n,p[5],m,i,k,j;
printf("\n Enter size of matrix : ");
scanf("%d",&m);
k=m+1;
printf("\n Enter values of p : ");
for(i=0;i<k;i++)
scanf(" %d",&p[i]);
matrix(p,k);
printf("\n Sequence:");
i=1,j=m;
solution(i,j);
return 0;
}
67 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
LCS: LNOP
68 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Algorithm:
1 LCS (X,Y)
2 m <- length[X]
3 n <- length[Y]
4 for I <- 1 to m
5 do c[i, 0] <- 0
6 for j <- 0 to n
7 do c[0, j] <- 0
8 for i <- 1 to m
9 do for j <- 1 to n
10 do if xi = yj
11 then c [i, j] <- c [i-1, j-1] + 1
12 b [i, j] <- “↖”
13 else if c [i-1, j] ≥ c [i, j-1]
14 then c [i, j] <- c [i-1, j]
15 b [i, j] <- “↑”
16 else c [i, j] <- c [i, j-1]
17 b [i, j] <- “←”
18 return c and b
Code:
#include<stdio.h>
int cmatrix[100][100];
char bmatrix[100][100], str[50], str1[50];
void main(){
int i,j,m,n,temp,temp1;
printf("\n Enter First Sequence : ");
scanf("%s",str);
fflush(stdin);
printf("\n Enter Second Sequence : ");
scanf("%s",str1);
fflush(stdin);
m=strlen(str);
n=strlen(str1);
for(i=0;i<=m;i++){
for(j=0;j<=n;j++){
if(i==0 || j==0){
cmatrix[i][j]=0;
bmatrix[i][j]='n';
}
else if(str[i-1]==str1[j-1]){
cmatrix[i][j]=cmatrix[i-1][j-1]+1;
bmatrix[i][j]='c';
}
else if(str[i-1]!=str1[j-1]){
69 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
if(cmatrix[i][j-1]>cmatrix[i-1][j]){
cmatrix[i][j]=cmatrix[i][j-1];
bmatrix[i][j]='l';
}
else{
cmatrix[i][j]=cmatrix[i-1][j];
bmatrix[i][j]='u';
}
}
}
}
printf("\n\n String Matrix:\n\n");
for(i=0;i<=m;i++){
printf("\t");
for(j=0;j<=n;j++){
printf("%d ",cmatrix[i][j]);
}
printf("\n");
}
printf("\n\n Arrow Matrix:\n\n");
for(i=0;i<=m;i++){
printf("\t");
for(j=0;j<=n;j++){
printf("%c ",bmatrix[i][j]);
}
printf("\n");
}
printf("\n LCS : ");
lcs(m,n);
}
void lcs(int i,int j){
if(i==0 || j==0){
return 0;
}
if (bmatrix[i][j]=='c'){
lcs(i-1,j-1);
printf("%c",str[i-1]);
}
else if (bmatrix[i][j]=='u'){
lcs(i-1,j);
}
else { lcs(i,j-1); }
}
70 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output :
71 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
PRACTICAL – 6
Aim: Graph
6.1 Print all the nodes reachable from a given starting node in a diagraph
using BFS method.
6.2 Check whether the graph is connected or not using DFS method.
6.3 From a given vertex in a weighted connected graph, find shortest paths to
other vertices using Dijkstra’s algorithm (Implement)
6.4 Find Minimum Cost spanning tree of a given undirected graph using
Kruskal’s algorithm.
6.5 Find Minimum Cost spanning tree of a given undirected graph using
Prim’s algorithm.
6.1 Print all the nodes reachable from a given starting node in a diagraph
using BFS method.
Theory:
- Breadth-first search (BFS) is an algorithm for traversing or
searching tree or graph data structures.
- It starts at the tree root and explores the neighbor nodes first, before moving to the
next level neighbors.
- The time complexity can be expressed as O(|V|+|E|), whereas the space complexity is
O(|V|).
- If the graph is represented by an adjacency list it occupies O(|V|+|E|) space in
memory, while an adjacency matrix representation occupies O(|V2|).
Example:
- BFS Sequence is : A B C D E F G H
72 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Algorithm:
Code:
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v)
{
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
void main()
{
int v;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf("\n Enter adjacency Matrix:\n\n");
73 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
for(i=1;i<=n;i++)
{
printf("\t");
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
}
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The sequence is:\n");
for(i=1;i<=n;i++)
if(visited[i])
printf(" %d",i);
else
printf("\n BFS is not possible");
}
Output :
6.2 Check whether the graph is connected or not using DFS method.
Theory:
Example:
- DFS Sequence is : A B C F E D G H
Algorithm:
1. visit [v] = 1;
2. for ( each vertex x adjacent from v)
3. if (visit [x] = 0 ) then
4. DFS(x)
Code:
#include<stdio.h>
int TOP=-1;
int stack[10];
void push(int a);
int pop();
void main()
{
int n,in[10]
[10],i,j,x=0,q,flag=0,start,current,visit[10]={0},connected[10]={0},count=0,path[10];
75 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
scanf(" %d",&in[i][j]);
}
}
q=n;
push(start-1);
visit[start-1]=1;
connected[start-1]=1;
while(q>0)
{
current=pop();
path[x]=current;
x++;
for(i=n-1;i>=0;i--)
{
if(in[current][i]==1 && visit[i]==0)
{
visit[i]=1;
connected[i]=1;
push(i);
}
}
q--;
}
while(TOP>=0)
{
current=pop();
visit[current]=1;
x--;
path[x]=current;
x++;
}
if(TOP==-1)
{
for(i=0;i<n;i++)
{
if(connected[i]==1)
{
count++;
}
}
}
if(count==n)
{
printf("\n Graph is Connected.\n\n The Sequence is : ");
76 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
6.3 From a given vertex in a weighted connected graph, find shortest paths
to other vertices using Dijkstra’s algorithm. (Implement)
Theory:
77 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
and finds shortest paths from the source to all other nodes in the graph, producing a shortest-
path tree.
- Time complexity is O(|V2|).
Example:
Source Vertex : 1
P Q R S T U
P 0 ∞ ∞ ∞ ∞ ∞
Q 1 ∞ 6 7 ∞
R 2 5 7 ∞
U 4 7 3
S 4 7
T 7
Algorithm:
prev[v] ← u
step6: return dist[], prev[]
Code:
#include<stdio.h>
void main()
{
int in[10][10], i, j, k=0, n, src, q, select[10], ans[10], dist=0,
solution[10][10], l=0, min=10000, p, count=0, f, flag=0, temp, count1=0;
79 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
min=temp;
p=i;
}
solution[l][i]=temp;
}
}
else
{
count++;
if(solution[l-1][i]==-1)
{
solution[l][i]=-1;
}
else if(select[i]==0)
{
solution[l][i]=solution[l-1][i];
}
}
}
ans[k]=p+1;
min=1000;
for(f=0;f<n;f++)
{
if(select[f]==1)
{
count1++;
}
}
if(count==n && count1==n-2)
{
src=ans[k-2]-1;
select[src]=0;
dist=dist-in[l-2][ans[k]-1];
count=0;
flag=1;
}
else
{
src=p;
dist=solution[l][p];
k++;
l++;
}
80 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
if(flag==0)
{
select[p]=1;
flag=0;
}
else
{
select[src]=1;
}
count=0;
count1=0;
q--;
}
printf("\n\n Solution:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(solution[i][j]!=-5)
{
printf("%4d",solution[i][j]);
}
else
{
printf(" ");
}
}
printf("\n");
}
printf("\n\n Path : ");
for(i=0;i<n;i++)
{
printf("%d ",ans[i]);
}
}
81 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
6.4 Find Minimum Cost spanning tree of a given undirected graph using
Kruskal’s algorithm.
Theory:
Example:
82 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Algorithm:
MST-KRUSKAL (G,w)
1. A ← ∅
2. for each vertex v ∈ V[G]
3. do MAKE-SET(v)
4. sort the edges of E into non-decreasing order by weight w
5. for each edge (u, v) ∈ E, taken in non-decreasing order by weight
6. do if FIND-SET(u) ≠ FIND-SET(v)
7. then A ← A ∪ {(u, v)}
8. UNION(u, v)
9. return A
6.5 Find Minimum Cost spanning tree of a given undirected graph using
Prim’s algorithm.
Theory:
83 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Example:
Algorithm:
MST-PRIM( G, w, r)
1. A={}
2. for each u ∈ V[G]
3. do key[u]←∞
4. π[u]← NIL
5. key[r] ← 0
6. Q ← V[G]
7. while Q = ∅
8. do u ← EXTRACT-MIN(Q)
9. Q=Q-u
10. If(π[u]!=NIL)
11. A=AU(u, π[u])
12. for each v ∈ Adj[u]
13. do if v ∈ Q and w(u, v) < key[v]
14. then π[v]← u
15. key[v] ← w(u, v)
Conclusion: From this practical, we have learnt about various algorithms for
finding MST, finding shortest path, searching in finite space and their
complexities and implementations of them.
84 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
PRACTICAL-7
Aim: Backtracking
7.1 Eight Queen Problem (Implement)
Algorithm:
1. Place the queens column wise, start from the left most column
2. If all queens are placed.
1. Return true and print the solution matrix.
3. Else
1. Try all the rows in the current column.
2. Check if queen can be placed here safely if yes mark the current cell in solu-
tion matrix as 1 and try to solve the rest of the problem recursively.
3. If placing the queen in above step leads to the solution return true.
4. If placing the queen in above step does not lead to the solu-
tion, BACKTRACK, mark the current cell in solution matrix as 0 and return false.
4. If all the rows are tried and nothing worked, return false and print NO SOLUTION.
85 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Example:
Code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
86 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
#define N 8
using namespace std;
void printSolution(int board[N][N]){
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout<<board[i][j]<<" ";
cout<<endl;
}
}
bool isSafe(int board[N][N], int row, int col){
int i, j;
for (i = 0; i < col; i++){
if (board[row][i])
return false;
}
for (i = row, j = col; i >= 0 && j >= 0; i--, j--){
if (board[i][j])
return false;
}
for (i = row, j = col; j >= 0 && i < N; i++, j--){
if (board[i][j])
return false;
}
return true;
}
bool solveNQUtil(int board[N][N], int col){
if (col >= N)
return true;
for (int i = 0; i < N; i++){
if ( isSafe(board, i, col) ){
board[i][col] = 1;
if (solveNQUtil(board, col + 1) == true)
return true;
board[i][col] = 0;
}
}
return false;
}
bool solveNQ(){
int board[N][N] = {0};
if (solveNQUtil(board, 0) == false){
cout<<"Solution does not exist"<<endl;
return false;
}
printSolution(board);
return true;
}
87 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
int main(){
solveNQ();
return 0;
}
Output:
Conclusion: From this practical, we have learnt how to solve an eight queen’s
problem using backtracking.
88 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
PRACTICAL-8
Aim: 1) Naïve String Matching (Implement)
2) Rabin Karp (Implement)
Software Required: CodeBlocks
Hardware Required: NA
Knowledge Required: Basic knowledge of c, c++
Theory:
Example:
- Text A B C A B A A B C A B A A
- Pattern
A B A A
- Valid Shifts: s=3, s=9
Algorithm:
NAIVE-STRING- MATCHER (T, P)
step1: n length[T]
step2: m length[P]
step3: for s 0 to n - m
do if P[1 . . m] = T[s + 1 . . s + m]
then print "Pattern occurs with shift" s
89 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Code:
#include<stdio.h>
void main(){
char t[100],p[100];
int tn,pn,shift[20]={0},s=0,i,j=0,count=0,m=0;
printf("\n Enter The Text : ");
scanf("%s",t);
fflush(stdin);
printf("\n Enter The Pattern : ");
scanf("%s",p);
tn = strlen(t);
pn = strlen(p);
while(s!=(tn-pn+1)){
j=0;
for(i=s;i<pn+s;i++){
if(p[j]==t[i]){
count++;
if(count==pn){
count=0;
shift[m]=s;
m++;
}
}else{
count=0;
break;
}
j++;
}
s++;
}
if(m>0){
90 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Pattern 2 6
- 26 mod 11 = 4
- Spurious hit : 15, 59, 92
- Valid hit : 26
Algorithm:
Rabin_Karp (string s [1...n], string pattern [1...m])
step1: hpattern: = hash (pattern [1...m]); hs: = hash (s [1...m])
step2: for i from 1 to n-m+1
91 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
if hs = hpattern
if s [i... i+m-1] = pattern [1...m]
return i
hs: = hash (s [i+1...i+m])
step3: return not found
Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>
#define d 10
void RabinKarpStringMatch(char [], char [], int);
void main(){
char Text[20],Pattern[20];
int Number = 11; //Prime Number
printf("\nEnter Text String : ");
gets(Text);
printf("\nEnter Pattern String : ");
gets(Pattern);
RabinKarpStringMatch(Text,Pattern,Number);
getch();
}
void RabinKarpStringMatch(char Text[], char Pattern[], int Number){
int M,N,h,P=0,T=0, TempT, TempP;
int i,j;
M = strlen(Pattern);
N = strlen(Text);
h = (int)pow(d,M-1) % Number;
for(i=0;i<M;i++) {
P = ((d*P) + ((int)Pattern[i])) % Number;
92 | P a g e
CE315 DESIGN & ANALYSIS OF ALGORITHM 15CE020
Output:
93 | P a g e