Vous êtes sur la page 1sur 69

Algorithm computation and complexity

14PGIT010

Practical 1
Write optimized iterative and recursive code for Fibonacci, factorial, GCD
and generate graph for input vs. count and make conclusion in your words.
1: Optimize a program for Fibonacci series using iteration and recursion draw graph of
input (N) vs. Count and write conclusion.
(1) Iteration
#include<stdio.h>
int Fibonacci(int);
int count;
void main()
{
int n, i, c;
count = 0;
count++;
i=0;
count++;
printf("enter terms n");
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
count++;
printf("%d\n", Fibonacci(i));
i++;
}

Algorithm computation and complexity

14PGIT010

printf("counter = %d",count);
}
int Fibonacci(int n)
{
if (n == 0 )
{
count++;
return 0;
}
else if ( n == 1 )
{
count++;
return 1;
}
else
{
count+=2;
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
count++;}

Algorithm computation and complexity

14PGIT010

(2) Recursion :
#include<stdio.h>
int count=0;
int Fibonacci(int);
void main()
{
int n, i = 0, c;
printf("enter n:");
scanf("%d",&n);
printf("Fibonacci series\n");
printf("%d\n", Fibonacci(i));
i++;
printf("count is= %d",count);
}
int Fibonacci(int n)
{
count+=2;
if ( n == 0 )
{
count++;
return 0;
}
else if ( n == 1 )
{
count++;
return 1;
}
else
{
count+=2;
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
count++;
}
3

Algorithm computation and complexity

14PGIT010

Table : Iteration
Input (N)

Output (count)

10

44

13

59

15

69

17

79

20

94

23

109

Table: Recursion

Input (N)

Output (count)

10

421

13

1816

15

4775

17

12525

20

53112

23

225051

Algorithm computation and complexity

14PGIT010

Graph: Iteration

Iteration
120
y = 5x - 6
100

109

94

80

79
69

60

Count

59

Linear (Count)

44

40
20
0
0

10

15

20

25

Graph: Recursion

Recursion
250000
y = 3.3937e0.4829x

225051

200000
150000
Count
100000

Expon. (Count)

50000
1816

421

12525

0
0

10

53112

4775
15

20

25

Conclusion: By examining both optimized code, output table and graph we conclude that for
Fibonacci iterative approach output less count than recursive hence execution is faster in iterative
approach with same input (N) .
5

Algorithm computation and complexity

14PGIT010

2: Optimize a program for Factorial series using iteration and recursion draw graph of
input (N) vs. Count and write conclusion.
(1) Iteration
#include<stdio.h>
int fact(int);
int count;
void main()
{
int n;
float fac;
count=0;
count++;
printf("Enter an integer: ");
scanf("%d",&n);
if ( n< 0)
{
printf("Error!!! Factorial of negative number doesn't exist.");
}
else
{
fac=fact(n);
}
printf("\nfactorial of %d is %f",n,fac);
printf("no of count=%d",count);
}
int fact(int n)
{
int i;
float factorial=1;
count++;
for(i=1;i<=n;i++) /* for loop terminates if count>n */
{
factorial*=i; /* factorial=factorial*count */
count=count+3;
}
count++;
6

Algorithm computation and complexity

14PGIT010

return factorial;
}

(2)Recursion:
#include<stdio.h>
int fact(int);
int count=0;
void main()
{
signed long int n,factorial=1;
printf("Enter any number : ");
scanf("%ld",&n);
factorial=fact(n);
printf("The factorial of %ld is %ld ",n,factorial);
printf("\ncount is= %d",count);
}
int fact(int n)
{
signed long int factorial=1;
count=+1;
if(n==1)
{
count++;
return 1;
}
else
{
count=count+1;
factorial=fact(n-1)*n;
}
count++;
return factorial;
}

Algorithm computation and complexity

14PGIT010

Table : Iteration
Input (N)

Output (count)

10

33

13

42

15

48

17

54

20

63

25

72

Table: Recursion

Input (N)

Output (count)

10

29

13

38

15

44

17

50

20

59

25

68

Algorithm computation and complexity

14PGIT010

Graph: Iteration

Iteration
80
y = 3x + 3

70

72

63

60
54

50

48

count

42

40

Linear (count)

33

30

Linear (count)

20
10
0
0

10

15

20

25

Graph: Recursion

Recursion
80
70

y = 3x - 1

60

59

50

68

50
44

40

Count

38

30

Linear (Count)

29

20
10
0
0

10

15

20

25

Conclusion: By examining optimized code, output table and graph we conclude that for
Factorial iterative approach and recursive approach both output is linear in graph. Order of
growth is proportional to N (input). But in recursive required less count than iterative hence
execution is faster in recursive approach with same input (N) .

Algorithm computation and complexity

14PGIT010

3: Optimize a program for GCD using iteration and recursion draw graph of input (N) vs.
Count and write conclusion.
(1) Iteration
#include<stdio.h>
void main()
{
int num1,num2,count=0;
count++;
printf("Enter two integers: ");
scanf("%d %d",&num1,&num2);
printf("GCD of %d and %d is ",num1 , num2);
while(num1!=num2)
{
count++;
if(num1>num2)
{
count++;
num1-=num2;
}
else
{
count++;
num2-=num1;
}
}
count++;
printf("gcd is = %d\n",num1);

10

Algorithm computation and complexity

14PGIT010

printf("count is %d\n", count);

(2)Recursion:
#include<stdio.h>
int count;
void main(){
int n1,n2,gcd;
count=0;
count++;
printf("\nEnter two numbers: ");
scanf("%d %d",&n1,&n2);
gcd=findgcd(n1,n2);
printf("\nGCD of %d and %d is: %d",n1,n2,gcd);
printf("\ncount = %d ",count);
}
int findgcd(int x,int y)
{
while(x!=y)
{
count++;
if(x>y)
{
count++;

11

Algorithm computation and complexity

14PGIT010

return findgcd(x-y,y);
}
else
{
count++;
return findgcd(x,y-x);
}
}
return x;
count++;
}

12

Algorithm computation and complexity

14PGIT010

Table : Iteration
N1

N2

Output (count)

23

11

26

34

17

67

11

34

11

12

24

N1

N2

Output (count)

23

11

25

34

17

67

11

33

11

12

23

Table: Recursion

Conclusion: by examining both iterative and recursive approach we conclude that for GCD
count or growths of both are independent of input values. Hence we can use any of them
approach.

13

Algorithm computation and complexity

14PGIT010

Practical 2
Implement and analyze algorithms of 1. Matrix Addition 2.Matrix
Multiplication using iteration and recursion also draw a graph and make
conclusion in own words.
1. Matrix addition using iteration.
I.

Program:-

#include <stdio.h>
int count;
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
count=0;
count++;
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
scanf("%d", &first[c][d]);
count=count+2;
}
}
printf("Enter the elements of second matrix\n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
scanf("%d", &second[c][d]);
count = count+2;
}
}
14

Algorithm computation and complexity

14PGIT010

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


{
for ( d = 0 ; d < n ; d++ )
{
sum[c][d] = first[c][d] + second[c][d];
count = count+3;
}
}
printf("Sum of entered matrices:-\n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
printf("%d\t", sum[c][d]);
}
printf("\n");
count = count +2;
}
printf("count = %d\n", count );
return 0;
}

15

Algorithm computation and complexity

II.

14PGIT010

Table:Matrix
1*1
2*2
3*3
4*4
5*5

III.

Count
10
33
70
121
186

Graph:-

Iterative
200
180
160
140
120
100
80
60
40
20
0

186

121
Count
70
33
10
0

Conclusion:By analyzing program and graph of matrix addition we conclude that count does not depend on
input but it depends on size of matrix if size increase count is also increase. Here we can also
conclude that order of growth is exponential.

16

Algorithm computation and complexity

14PGIT010

2. Matrix multiplication using iteration.


I.

Program:-

#include<stdio.h>
int count;
int main()
{
count =0;
int a[10][10],b[10][10],c[10][10],i,j,k,sum=0,m,n,o,p;
count=count+2;
printf("\nEnter the row and column of first matrix");
scanf("%d %d",&m,&n);
printf("\nEnter the row and column of second matrix");
scanf("%d %d",&o,&p);
if(n!=o)
{
count++;
printf("Matrix mutiplication is not possible");
printf("\nColumn of first matrix must be same as row of second matrix");
}
Else
{
count++;
printf("\nEnter the First matrix->");
for(i=0;i<m;i++)
{
count++;
17

Algorithm computation and complexity

14PGIT010

for(j=0;j<n;j++)
{
count++;
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix->");
for(i=0;i<o;i++)
{
count++;
for(j=0;j<p;j++)
{
count++;
scanf("%d",&b[i][j]);
}
}
printf("\nThe First matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");

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

Algorithm computation and complexity

14PGIT010

printf("\nThe Second matrix is\n");


for(i=0;i<o;i++)
{
printf("\n");
for(j=0;j<p;j++)
{
printf("%d\t",b[i][j]);
}
}
for(i=0;i<m;i++)
{
count++;
for(j=0;j<p;j++)
{
count++;
c[i][j]=0;
count++;
}
}
for(i=0;i<m;i++)
{ //row of first matrix
for(j=0;j<p;j++)
{ //column of second matrix
sum=0;
count= count+3;
for(k=0;k<n;k++)
{
19

Algorithm computation and complexity

14PGIT010

sum=sum+a[i][k]*b[k][j];
count = count+3;
c[i][j]=sum;
}
}
}
}
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<p;j++)
{
count=count+2;
printf("%d\t",c[i][j]);
}
}
count++;
printf("count is = %d",count);
return 0;
}
II.

Table:Matrix
1*1
2*2
3*3
4*4
5*5

Count
19
70
175
352
619

20

Algorithm computation and complexity

III.

14PGIT010

Graph:-

Iterative
700

619

600
500
400

352
300
200

175

100

70
19

0
1*1

2*2

3*3

4*4

5*5

Conclusion:By analyzing program and graph of matrix multiplication we conclude that count does not
depend on input but it depends on size of matrix. if size increase count is also increase. Here we
can also conclude that order of growth is exponential.

21

Algorithm computation and complexity

14PGIT010

Practical: - 3
Perform Sorting Using Insertion Sort, Selection Sort, and Bubble Sort And
Analyze Complexity.
1) Insertion Sort

#include<stdio.h>
int cnt=0;
int swap=0;
int comp=0;
int main()
{
int i,j,num,temp,a[100];
printf("Enter total elements: ");
scanf("%d",&num);

printf("Enter %d elements: ",num);

for(i=0;i<num;i++)
{

scanf("%d",&a[i]);
cnt+=2;
}
for(i=1;i<num;i++)
{
22

Algorithm computation and complexity

14PGIT010

comp++;
temp=a[i];
j=i-1;

while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j];
j=j-1;
cnt+=4;
swap++;
comp++;
}
a[j+1]=temp;

}
printf("After Sorting: ");

for(i=0;i<num;i++)
{
printf("%d\n",a[i]);
}
printf("Count is:%d \n",cnt);
printf("Comp is:%d \n",comp);
printf("Swap is:%d \n",swap);
23

Algorithm computation and complexity

14PGIT010

return 0;
}

Input WORST

AVERAGE

BEST

SWAP

COMP

SWAP

COMP

SWAP

COMP

10

14

21

27

15

10

45

54

29

38

Best case:
25

y = -4E-15x2 + 2x - 2E-13

20

15
Series1
Poly. (Series1)

10

0
0

24

10

12

Algorithm computation and complexity

14PGIT010

Avg. case:-

160
140

y = 3.3333x2 - 28x + 82.667

120
100
Series1
80

Series2

60

Poly. (Series2)

40
20
0
0

10

12

Worst case:-

250

y = 2x2 + 2E-13x - 1E-12

200

150
Series1
Poly. (Series1)

100

50

0
0

25

10

12

Algorithm computation and complexity

14PGIT010

2) Selection Sort
#include <stdio.h>
int main()
{
int array[100], n, c, d, position, swap=0,count=0,SWAP=0,COMP=0;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
{
scanf("%d", &array[c]);
}
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
count+=2;
position = c;
count++;
for ( d = c ; d < n ; d++ )
{
count+=2;
COMP++;
if ( array[position] > array[d] )
{
position = d;
count+=2;
26

Algorithm computation and complexity

14PGIT010

}
count++;
COMP++;
if ( position != c )
{
count++;
swap = array[c];
array[c] = array[position];
array[position] = swap;
count+=3;
SWAP++;
} }
count++;
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
{
printf("%d\n", array[c]);

}
printf("number of count=%d",count);
printf("number of SWAP=%d",SWAP);
printf("number of COMP=%d",COMP);
}

27

Algorithm computation and complexity

14PGIT010

Input WORST

AVERAGE

BEST

SWAP

COMP

SWAP

COMP

SWAP

COMP

10

20

20

20

21

42

15

42

42

10

45

90

44

90

90

Best case:
180
y = 1.5x2 + 2.5x - 4

160
140
120
100

Series1

80

Poly. (Series1)

60
40
20
0
0

10

12

Avg. case:
450
400

y = 12.367x2 - 122.9x + 385.33

350
300
250

Series1

200

Poly. (Series1)

150
100
50
0
0

28

10

12

Algorithm computation and complexity

14PGIT010

Worst case:

count
120
y = 1.6x2 - 8.2x + 27

100
80

count

60

Poly. (count)

40
20
0
0

10

3) Bubble Sort
#include <stdio.h>
int main(){
int array[100], n, c, d, swap,COUNT=0,COMP=0,SWAP=0;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{ COUNT++;
for (d = 0 ; d < n - c - 1; d++)
{
29

12

Algorithm computation and complexity

14PGIT010

COMP++; COUNT++;
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap

= array[d];

array[d] = array[d+1];
array[d+1] = swap;
COUNT=COUNT+3;
SWAP++;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ ) {
printf("%d\n", array[c]);
}
printf("NUMBER OF SWAP=%d",SWAP);
printf("NUMBER OF COUNT=%d",COUNT);
printf("\nNUMBER OF COMP=%d",COMP);
}

30

Algorithm computation and complexity

14PGIT010

Input WORST

AVERAGE

BEST

SWAP

COMP

SWAP

COMP

SWAP

COMP

10

10

10

10

21

21

21

21

10

45

45

17

45

45

Best case:

count
60

54

y = 0.5x2 + 0.5x - 1
40

count

27

20

Poly. (count)

14

0
0

10

12

Avg. case:
120
y = 1.6x2 - 8.2x + 27

100
80
60

Series1

40

Poly. (Series1)

20
0
0

31

10

12

Algorithm computation and complexity

14PGIT010

Worst case:
200
y = 2x2 - 1x - 1
150
Series1

100

Poly. (Series1)
50
0
0

10

12

Final count table:


input

Insertion sort

Selection sort

Bubble sort

Best

Avg.

Worst

Best

Avg.

Worst

Best

Avg.

Worst

case

case

case

case

case

case

case

case

case

10

26

50

46

80

106

14

26

44

14

50

98

87

131

213

27

48

90

10

20

136

200

171

393

441

54

105

189

Conclusion:- In this three method complexity is depend on input size as well as input quality.
And complexity in terms of O (n2) in worst cases.

32

Algorithm computation and complexity

14PGIT010

Practical-4
Write a code for given methods and perform analysis by graph and table.
1) Merge Sort
2) Quick Sort
3) Binary Search
1. Merge Sort
#include<stdio.h>
int count =0,comp =0,swap=0;
void merge(int [],int ,int ,int );
void part(int [],int ,int );
void main()
{
Int arr[30];
Int i,size;
printf("\n\t------- Merge sorting method -------\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
count++;
printf("\n\t------- Merge sorted elements -------\n\n");
for(i=0; i<size; i++)
33

Algorithm computation and complexity

14PGIT010

printf("%d ",arr[i]);
printf("\n count == %d\n",count);
printf("\n comp == %d\n",comp);
printf("\n swap == %d\n",swap);
}
void part(intarr[],intmin,int max)
{
int mid;
count++;
if(min<max)
{
comp++;
count++;
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
count= count+3;
merge(arr,min,mid,max);
count++;
}
}
void merge(intarr[],intmin,intmid,int max)
{
Int tmp[30];
Int i,j,k,m;
count++;
j=min;
34

Algorithm computation and complexity

14PGIT010

m=mid+1;
count=count+2;
for(i=min; j<=mid && m<=max ; i++)
{
comp++;
count++;
if(arr[j]<=arr[m])
{
comp++;
count=count+2;
tmp[i]=arr[j];
j++;
swap++;
}
else
{
tmp[i]=arr[m];
m++;
count=count+2;
swap++;
}
}
if(j>mid)
{
comp++;
count++;
for(k=m; k<=max; k++)
35

Algorithm computation and complexity

14PGIT010

{
tmp[i]=arr[k];
i++;
count=count+2;
swap++;
}
}
else
{
count++;
for(k=j; k<=mid; k++)
{
tmp[i]=arr[k];
i++;
count=count+2;
swap++;
}
}
for(k=min; k<=max; k++){
arr[k]=tmp[k];
count=count+2;
}
}

36

Algorithm computation and complexity

14PGIT010

Table:Size
of Worst case count
array (N)

Avg. case count

Best case count

47

47

46

101

102

99

159

162

157

222

226

219

11

290

295

285

Worst case:350
300
y = 182.21ln(x) - 173.26
222

250
200

290
Series1

159

150
100

Log. (Series1)

101

50

47

0
0

10

12

Avg. case:350
300
y = 186.18ln(x) - 178

250
200

Series1

150

Log. (Series1)

100
50
0
0

37

10

12

Algorithm computation and complexity

14PGIT010

Best case:300
y = 179.61ln(x) - 171.04

250
200

Series1

150

Log. (Series1)

100
50
0
0

10

12

Conclusion:Here we conclude that time complexity of merge sort in best, worst, avg. case are same that
is O(logN).

38

Algorithm computation and complexity

14PGIT010

2. Binary Search
#include <stdio.h>
Void main()
{
int c, first, last, middle, n, search, array[100],ccount=0;
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d",&search);
first = 0;
last = n - 1;
middle = (first+last)/2;
ccount=ccount+3;
while( first <= last )
{
ccount++;
if ( array[middle] < search )
{

39

Algorithm computation and complexity

14PGIT010

ccount++;
first = middle + 1;
ccount++;
}
else if ( array[middle] == search )
{
ccount++;
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
{
ccount++;
last = middle - 1;
ccount++;
}

middle = (first + last)/2;


ccount++;
}
if ( first > last )

40

Algorithm computation and complexity

14PGIT010

{
ccount++;
printf("Not found! %d is not present in the list.\n", search);
}
printf("\n count= %d\n ",ccount);

}
Table:Size of array

worst / avg case

Best case count

count
3

13

13

11

13

Worst and avg. case count:-

worst / avg case count


15
y = 0.6x + 7.2
10

worst / avg case count

Linear (worst / avg case


count)

0
0

10

41

12

Algorithm computation and complexity

14PGIT010

Best case count:1.2


1

y=1

0.8
Size of array
0.6

Best case count

0.4

Linear (Best case count)

0.2
0
0

Conclusion:Here we conclude that for binary search complexity in worst and avg. case are same that is
O(logN) and best case O(1).

42

Algorithm computation and complexity

14PGIT010

3. Quick Sort
#include<stdio.h>
int count =0,swap = 0,comp =0;
void quicksort(int [10],int,int);
void main(){
int x[20],size,i;
printf("Enter size of the array: ");
scanf("%d",&size);
printf("Enter %d elements: ",size);
for(i=0;i<size;i++)
scanf("%d",&x[i]);
quicksort(x,0,size-1);
count++;
printf("Sorted elements: ");
for(i=0;i<size;i++)
printf(" %d",x[i]);
printf("\n count == %d\n",count);
printf("\n swap == %d\n",swap);
printf("\n comp == %d\n",comp);

43

Algorithm computation and complexity

14PGIT010

void quicksort(int x[10],intfirst,int last){


intpivot,j,temp,i;
count++;
if(first<last){
comp++;
pivot=first;
i=first;
j=last;
count= count+4;
while(i<j){
count++;
while(x[i]<=x[pivot]&&i<last)
{
count++;
comp++;
i++;
}
while(x[j]>x[pivot])
{
comp++;
count++;

44

Algorithm computation and complexity

14PGIT010

j--;
}
if(i<j)
{
temp=x[i];
x[i]=x[j];
x[j]=temp;
count=count+4;
swap++;
}
}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
swap++;
quicksort(x,first,j-1);
quicksort(x,j+1,last);
count = count+5;
}
}

45

Algorithm computation and complexity

14PGIT010

Table:Size of array (N)

Worst case

Avg. case

Best case

31

22

16

64

47

44

101

86

82

142

101

98

11

187

155

149

Worst case:-

Worst case
200
180
160
140
120
100
80
60
40
20
0

y = 0.5x2 + 12.5x - 11

Worst case
Poly. (Worst case)

46

10

12

Algorithm computation and complexity

14PGIT010

Avg. case:-

Avg. case
180
160
140
120
100
80
60
40
20
0

y = 95.477ln(x) - 94.415
Avg. case
Log. (Avg. case)

10

12

Best case:-

Best case
160
140

y = 95.965ln(x) - 99.717

120
100
80

Best case

60

Log. (Best case)

40
20
0
0

10

12

Conclusion:Here we conclude that in quick sort time complexity in worst case is O(N2) and in best case
O(logn) and avg. case O(ln N).

47

Algorithm computation and complexity

14PGIT010

Practical 5
Write a C program for following two methods and find complexity
1) Knapsack problem
2) Making change problem
1) Knapsack problem:#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,w[50],v[50],p[50],item[50],W,i,j,temp,amount,solution[50],max_value=0;
printf("Enter the number of items ::");
scanf("%d",&n);
printf("Enter the weights and value of each items ::\n");
printf("Item\tWeights\tValue\n");
printf("-----------------------\n");
for(i=0;i<n;i++)
{
item[i]=i+1;
printf("I[%d]\t",item[i]);
scanf("%d",&w[i]);
scanf("%d",&v[i]);

}
printf("Enter the capacity of knapsack ::\n");
scanf("%d",&W);
48

Algorithm computation and complexity

14PGIT010

for(i=0;i<n;i++)
{
p[i]=(v[i]/w[i]);
}
printf("\n");
printf("Item\tWeights\tValue\tratio(pi)\n");
printf("--------------------------------\n");
for(i=0;i<n;i++)
{
printf("I[%d]\t",item[i]);
printf("%d\t",w[i]);
printf("%d\t",v[i]);
printf("%d\n",p[i]);
}
printf("\n");
printf("Arrange the value of pi in decreasing order ::\n");
/*using sort to sort pi in decreasing order*/
for(i=n-2;i>=0;i--)
{
for(j=0;j<=i;j++)
{
if(p[j]<p[j+1])
{
temp=v[j+1];
v[j+1]=v[j];
49

Algorithm computation and complexity

14PGIT010

v[j]=temp;
temp=w[j+1];
w[j+1]=w[j];
w[j]=temp;
temp=item[j+1];
item[j+1]=item[j];
item[j]=temp;
temp=p[j+1];
p[j+1]=p[j];
p[j]=temp;

}
}
}
printf("\n");
printf("Item\tWeights\tValue\tratio(pi)\n");
printf("--------------------------------\n");
for(i=0;i<n;i++)
{
printf("I[%d]\t",item[i]);
printf("%d\t",w[i]);
printf("%d\t",v[i]);
printf("%d\n",p[i]);
}
printf("\n");
50

Algorithm computation and complexity

14PGIT010

printf("The solution of Knapsack problems using Greedy Algorithm is::\n");


i=0;
while(W>0)
{
if(w[i]<W)
{
amount=w[i];
max_value=max_value+v[i];
}
else
{
amount=W;
max_value=max_value+((v[i]/w[i])*W);
}
//amount=min(W,w[i]);
solution[i]=amount;
printf("%d\t",solution[i]);
W=W-amount;

i=i+1;
}
printf("\n");
printf("The maximum value is ::%d\n",max_value);

return 0;
51

Algorithm computation and complexity

14PGIT010

}
Output:-

Conclusion:Complexity of knapsack problem is O(n).

2) Making change:#include<stdio.h>
void make_change(int);
int bestsol(int,int);
int C[5]={1,5,10,25,100};
void main()
{
int n,n1,i;
printf("\n------------------------------------------------");
printf("\n

MAKING CHANGE USING GREEDY ALGORITHM

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

");

Algorithm computation and complexity

14PGIT010

printf("\n Enter amount you want:");


scanf("%d",&n);
make_change(n);
}
void make_change(int n)
{
int S[100],s=0,x,ind=0,i;
printf("\n----------------AVAILABLE COINS-----------------\n");
for(i=0;i<= 4;i++)
printf("%5d",C[i]);
printf("\n------------------------------------------------");
while(s!=n)
{
x=bestsol(s,n);
if(x==-1)
{}
else
{
S[ind++]=x;
s=s+x;
}
}
printf("\n-------------MAKING CHANGE FOR %4d-------------",n);
for(i=0;i < ind;i++)
{
53

Algorithm computation and complexity

14PGIT010

printf("\n%5d",S[i]);
}
printf("\n------------------------------------------------");
}
int bestsol(int s,int n)
{
int i;
for(i=4;i>-1;i--)
{
if((s+C[i]) <= n)
return C[i] ;
}
return -1;
}
Output:-

Conclusion: - complexity of making change problem using greedy is O(nlogn).

54

Algorithm computation and complexity

14PGIT010

Practical 6
Design algorithm using greedy approach.
Question:- Suppose you were to drive from station Louis to Denver along I-70. Your gas tank,
when full, holds enough gas to travel m miles, and you have a map that gives distances between
gas stations along the route. Let d1<d2 <.. < dn be the locations of all the gas stations along the
route where di is the distance from station Louis to the gas station. You can assume that the
distance between neighbouring gas stations is at most m miles.
Your goal is to make as few gas stops as possible along the way. Give the most efficient
algorithm to determine at which gas stations you should stop and prove that your strategy yields
an optimal solution. Be sure to give the time complexity of your algorithm as a function of n.

Solution:The greedy algorithm we use is to go as far as possible before stopping for gas. Let ci
be the city with distance di from St. Louis. Here is the pseudo-code.
S=;
last = 0
for i = 1 to n
if (dilast > m)
S = S [ fci]
glast = ti1
Clearly the above is an O(n) algorithm. We now prove it is correct.
Greedy Choice Property: Let S be an optimal solution. Suppose that its sequence of stops is s1;
s2;:::;sk where si is the stop corresponding to distance ti. Suppose that g is the rst stop made by
the above greedy algorithm. We now show that there is
an optimal solution with a rst stop at g. If S s1 = g then S is such a solution. Now suppose that s1
6= g. Since the greedy algorithm stops at the latest possible city then it follows that s1 is before
g. We now argue that S0 = hg; s2; s3;:::;sk i is an optimal solution. First note that |S0| = |S|.
Second, we argue that S0 is legal (i.e. you never run out of gas). By denition of the greedy choice
you can reach g. Finally, since S is optimal and the distance between g and s2 is no more than the
distance between s1
and s2, there is enough gas to get from g to s2. The rest of S0 is like S and thus legal.

Optimal Substructure Property: Let P be the original problem with an optimal


solution S. Then after stopping at the station g at distance di the subproblem P 0 that
remains is given by di+1;:::;dn (i.e. you start at the current city instead of St. Louis).
2Let S0 be an optimal solution to P 0. Since, cost(S) = cost(S0) + 1, clearly an optimal
solution to P includes within it an optimal solution to P

55

Algorithm computation and complexity

14PGIT010

Practical 8
Design any one (Dynamic Programming)
8.1 Find the minimum of characters to be inserted to convert it into
palindrome.

// A Naive recursive program to find minimum number insertions


// needed to make a string palindrome
#include <stdio.h>
#include <limits.h>
#include <string.h>

// A utility function to find minimum of two numbers


int min(int a, int b)
{ return a < b ? a : b; }

// Recursive function to find minimum number of insersions


int findMinInsertions(char str[], int l, int h)
{
// Base Cases
if (l > h) return INT_MAX;
if (l == h) return 0;
if (l == h - 1) return (str[l] == str[h])? 0 : 1;

// Check if the first and last characters are same. On the basis of the
// comparison result, decide which subrpoblem(s) to call
56

Algorithm computation and complexity

14PGIT010

return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1):


(min(findMinInsertions(str, l, h - 1),
findMinInsertions(str, l + 1, h)) + 1);
}

// Driver program to test above functions


int main()
{
char str[] = "geeks";
printf("palindrome for geeks is %d", findMinInsertions(str, 0, strlen(str)-1));
return 0;
}

Output:

57

Algorithm computation and complexity

14PGIT010

Practical 9
Implement and analyze the problem.
9.1 Eight Queen Problem
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int x[10];
int cnt=0;
int place(int k,int i)
{
int j;
cnt++;
for(j=1;j<=k;j++)
{
cnt+=2;
if(x[j]==i || (abs(x[j]-i))==(abs(j-k)))
{
cnt+=2;
return 0;
}
}
return 1;
}
58

Algorithm computation and complexity

14PGIT010

void queen(int k,int n)


{
int i,j;
cnt++;
for(i=1;i<=n;i++)
{
cnt+=2;
if(place(k,i))
{
cnt+=2;
x[k]=i;
if(k==n)
{
cnt++;
for(j=1;j<=n;j++)
printf("%d \t",x[j]);
}
else
{
cnt+=2;
queen(k+1,n);
}
}
}
}
59

Algorithm computation and complexity

14PGIT010

void main()
{
int n,k=1;
clock_t start,end;
clrscr();
start=clock();
printf("Enter the size of chess board:");
scanf("%d",&n);
queen(k,n);
cnt++;
end=clock();
printf("\n counter: %d",cnt);
printf("\n running time is=%f",(end-start)/CLK_TCK);
getch();
}

Output:

60

Algorithm computation and complexity

14PGIT010

Practical 10
Design any two from 10.1 to 10.4.( Graph)
10.2 Given an undirected graph and a number m, determine if the graph can
be colored with at most m colors such that no two adjacent vertices of the
graph are colored with same color. Here coloring of a graph means
assignment of colors to all vertices. Solve this using Backtracking.
Implementation of Backtracking solution
#include<stdio.h>
// Number of vertices in the graph
#define V 4
void printSolution(int color[]);

/* A utility function to check if the current color assignment


is safe for vertex v */
bool isSafe (int v, bool graph[V][V], int color[], int c)
{
for (int i = 0; i < V; i++)
if (graph[v][i] && c == color[i])
return false;
return true;
}

/* A recursive utility function to solve m coloring problem */


bool graphColoringUtil(bool graph[V][V], int m, int color[], int v)

61

Algorithm computation and complexity

14PGIT010

{
/* base case: If all vertices are assigned a color then
return true */
if (v == V)
return true;

/* Consider this vertex v and try different colors */


for (int c = 1; c <= m; c++)
{
/* Check if assignment of color c to v is fine*/
if (isSafe(v, graph, color, c))
{
color[v] = c;

/* recur to assign colors to rest of the vertices */


if (graphColoringUtil (graph, m, color, v+1) == true)
return true;

/* If assigning color c doesn't lead to a solution


then remove it */
color[v] = 0;
}
}

/* If no color can be assigned to this vertex then return false */


62

Algorithm computation and complexity

14PGIT010

return false;
}

/* This function solves the m Coloring problem using Backtracking.


It mainly uses graphColoringUtil() to solve the problem. It returns
false if the m colors cannot be assigned, otherwise return true and
prints assignments of colors to all vertices. Please note that there
may be more than one solutions, this function prints one of the
feasible solutions.*/
bool graphColoring(bool graph[V][V], int m)
{
// Initialize all color values as 0. This initialization is needed
// correct functioning of isSafe()
int *color = new int[V];
for (int i = 0; i < V; i++)
color[i] = 0;

// Call graphColoringUtil() for vertex 0


if (graphColoringUtil(graph, m, color, 0) == false)
{
printf("Solution does not exist");
return false;
}

// Print the solution


63

Algorithm computation and complexity

14PGIT010

printSolution(color);
return true;
}

/* A utility function to print solution */


void printSolution(int color[])
{
printf("Solution Exists:"
" Following are the assigned colors \n");
for (int i = 0; i < V; i++)
printf(" %d ", color[i]);
printf("\n");
}

// driver program to test above function


int main()
{
bool graph[V][V] = {{0, 1, 1, 1},
{1, 0, 1, 0},
{1, 1, 0, 1},
{1, 0, 1, 0},
};
int m = 3; // Number of colors
graphColoring (graph, m);
return 0;
64

Algorithm computation and complexity

14PGIT010

10.3 Subset sum problem is to find subset of elements that are selected from
a given set whose sum adds up to a given number K. We are considering the
set contains non-negative values. It is assumed that the input set is unique (no
duplicates are presented). Solve this using Backtracking
#include <stdio.h>
#include <stdlib.h>

#define ARRAYSIZE(a) (sizeof(a))/(sizeof(a[0]))

static int total_nodes;


// prints subset found
void printSubset(int A[], int size)
{
int i;
for(i = 0; i < size; i++)
{
printf("%*d", 5, A[i]);
}

printf("\n");
}

// inputs
// s

- set vector
65

Algorithm computation and complexity

// t

14PGIT010

- tuplet vector

// s_size

- set size

// t_size

- tuplet size so far

// sum

- sum so far

// ite

- nodes count

// target_sum - sum to be found


void subset_sum(int s[], int t[],
int s_size, int t_size,
int sum, int ite,
int const target_sum)
{
total_nodes++;
if( target_sum == sum )
{
// We found subset
printSubset(t, t_size);
// Exclude previously added item and consider next candidate
subset_sum(s, t, s_size, t_size-1, sum - s[ite], ite + 1, target_sum);
return;
}
else
{
// generate nodes along the breadth
int i;
for( i = ite; i < s_size; i++ )
66

Algorithm computation and complexity

14PGIT010

{
t[t_size] = s[i];
// consider next level node (along depth)
subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);
}
}
}

// Wrapper to print subsets that sum to target_sum


// input is weights vector and target_sum
void generateSubsets(int s[], int size, int target_sum)
{
int *tuplet_vector = (int *)malloc(size * sizeof(int));

subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum);

free(tuplet_vector);
}

int main()
{
int weights[] = {10, 7, 5, 18, 12, 20, 15};
int size = ARRAYSIZE(weights);

generateSubsets(weights, size, 35);


67

Algorithm computation and complexity

14PGIT010

printf("Nodes generated %d\n", total_nodes);


return 0;
}

Output:

68

Algorithm computation and complexity

14PGIT010

Practical 11
Suppose you are playing game of shooting balloon. You expect to shoot n
balloons in the board, assuming you are sharpshooter, 100% hit. There are
two scenarios, you need find the appropriate Big Oh notation for each
scenario. In these problems, one unit of work is shooting one balloon.
11.1 For every 2 balloons you are able to shoot, one new balloon is inserted in
the board. So, if there were 20 balloons, after you shoot the first 2, there are
19 on the board. After you shoot the next 2, there are 18 on the board. How
many balloons do you shoot before the board is empty?
A: O(1)
B: O(n)
C: O(lgn)

D: O(n)
11.2 By the time you have shoot the first n balloons, n-1 new balloons have
been inserted on the board. After shooting those n-1 balloons, there are n-2
new balloons are inserted on the board. After checking out those n-2 balloons ,
there are n-3 new balloons on the board. This same pattern continues until on
new balloon are inserted on the board. How many total balloons do you
shoot before the board is empty?

A: O(1)
B: O(n)
C: O(lgn)

D: O(n)

69

Vous aimerez peut-être aussi