algorithm and computation complexity

81
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++; 1

Upload: krupanick24

Post on 18-Jul-2016

20 views

Category:

Documents


1 download

DESCRIPTION

daa list

TRANSCRIPT

Page 1: Algorithm and Computation Complexity

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++;

}

printf("counter = %d",count);

1

Page 2: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

}

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++;}

(2) Recursion :

2

Page 3: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

#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++;}

Table : Iteration

3

Page 4: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

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

Graph: Iteration

4

Page 5: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

8 10 12 14 16 18 20 22 240

20

40

60

80

100

120

44

5969

79

94

109f(x) = 5 x − 6

Iteration

CountLinear (Count)

Graph: Recursion

8 10 12 14 16 18 20 22 240

50000

100000

150000

200000

250000

421 18164775

12525

53112

225051f(x) = 3.39373101412293 exp( 0.482921597983301 x )

Recursion

CountExponential (Count)

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) .

2: Optimize a program for Factorial series using iteration and recursion draw graph of input (N) vs. Count and write conclusion.

5

Page 6: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

(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++;return factorial;

}

6

Page 7: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

(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;

}

Table : Iteration

Input (N) Output (count)

7

Page 8: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

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

Graph: Iteration

8

Page 9: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

8 10 12 14 16 18 20 22 240

10

20

30

40

50

60

70

80

33

4248

54

63

72f(x) = 3 x + 3f(x) = 3 x + 3

Iteration

countLinear (count)Linear (count)

Graph: Recursion

8 10 12 14 16 18 20 22 240

10

20

30

40

50

60

70

80

29

3844

50

59

68f(x) = 3 x − 1

Recursion

CountLinear (Count)

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) .

3: Optimize a program for GCD using iteration and recursion draw graph of input (N) vs. Count and write conclusion.

9

Page 10: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

(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);

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

10

Page 11: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

}

(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++;

return findgcd(x-y,y);

}

11

Page 12: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

else

{

count++;

return findgcd(x,y-x);

}

}

return x;

count++;

}

Table : Iteration

N1 N2 Output (count)

12

Page 13: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

1 1 2

2 8 8

23 11 26

34 17 4

67 11 34

11 12 24

Table: Recursion

N1 N2 Output (count)

1 1 1

2 8 7

23 11 25

34 17 3

67 11 33

11 12 23

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.

Practical 2

13

Page 14: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

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; } } for ( c = 0 ; c < m ; c++ )

14

Page 15: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

{ 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;}

II. Table:-

15

Page 16: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Matrix Count1*1 102*2 333*3 704*4 1215*5 186

III. Graph:-

0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.50

20

40

60

80

100

120

140

160

180

200

10

33

70

121

186

Iterative

Count

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.

2. Matrix multiplication using iteration.

16

Page 17: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

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++;

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

17

Page 18: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

{

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]);

}

}

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

18

Page 19: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

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++)

{

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

19

Page 20: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

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 Count1*1 192*2 703*3 1754*4 3525*5 619

III. Graph:-

20

Page 21: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

1*1 2*2 3*3 4*4 5*50

100

200

300

400

500

600

700

1970

175

352

619

Iterative

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

Page 22: Algorithm and Computation Complexity

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

Page 23: Algorithm and Computation Complexity

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

Page 24: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

return 0;

}

Best case:

4 5 6 7 8 9 10 110

5

10

15

20

25

f(x) = 1.82503316251144E-16 x² + 2 x + 1.02558009940457E-14

Series2Polynomial (Series2)

24

Input

WORST

AVERAGE BEST

SWAP COMP SWAP COMP SWAP COMP

5 10 14 4 8 0 4

7 21 27 9 15 0 6

10 45 54 29 38 0 9

Page 25: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Avg. case:-

4 5 6 7 8 9 10 110

20

40

60

80

100

120

140

160

f(x) = 3.33333333333333 x² − 28 x + 82.6666666666666

Series2Series4Polynomial (Series4)

Worst case:-

4 5 6 7 8 9 10 110

50

100

150

200

250

f(x) = 2 x²

Series2Polynomial (Series2)

25

Page 26: Algorithm and Computation Complexity

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

Page 27: Algorithm and Computation Complexity

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

Page 28: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Best case:

4 5 6 7 8 9 10 110

20

40

60

80

100

120

140

160

180

f(x) = 1.5 x² + 2.50000000000005 x − 4.0000000000002

Series2Polynomial (Series2)

Avg. case:

4 5 6 7 8 9 10 110

50

100

150

200

250

300

350

400

450

f(x) = 12.3666666666667 x² − 122.9 x + 385.333333333333

Series2Polynomial (Series2)

28

Input

WORST

AVERAGE BEST

SWAP COMP SWAP COMP SWAP COMP

5 10 20 6 20 0 20

7 21 42 15 42 0 42

10 45 90 44 90 0 90

Page 29: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Worst case:

4 5 6 7 8 9 10 110

20

40

60

80

100

120

f(x) = 1.6 x² − 8.19999999999999 x + 27f(x) = 1.6 x² − 8.19999999999999 x + 27

count

countPolynomial (count)Polynomial (count)

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

Page 30: Algorithm and Computation Complexity

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

Page 31: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Best case:

4 5 6 7 8 9 10 110

10

20

30

40

50

60

14

27

54f(x) = 0.5 x² + 0.500000000000001 x − 1.00000000000001

count

countPolynomial (count)

Avg. case:

4 5 6 7 8 9 10 110

20

40

60

80

100

120

f(x) = 1.6 x² − 8.19999999999999 x + 27

Series2Polynomial (Series2)

31

Input

WORST

AVERAGE BEST

SWAP COMP SWAP COMP SWAP COMP

5 10 10 4 10 0 10

7 21 21 7 21 0 21

10 45 45 17 45 0 45

Page 32: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Worst case:

4 5 6 7 8 9 10 110

20

40

60

80

100

120

140

160

180

200

f(x) = 2 x² − 0.999999999999997 x − 1.00000000000002

Series2Polynomial (Series2)

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

5 10 26 50 46 80 106 14 26 44

7 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

Page 33: Algorithm and Computation Complexity

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

Page 34: Algorithm and Computation Complexity

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

Page 35: Algorithm and Computation Complexity

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

Page 36: Algorithm and Computation Complexity

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;

}

}

Size of Worst case count Avg. case count Best case count

36

Page 37: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

array (N)

3 47 47 46

5 101 102 99

7 159 162 157

9 222 226 219

11 290 295 285

Table:-

Worst case:-

2 3 4 5 6 7 8 9 10 11 120

50

100

150

200

250

300

350

47

101

159

222

290

f(x) = 182.212765611824 ln(x) − 173.260096532158

Series2Logarithmic (Series2)

Avg. case:-

2 3 4 5 6 7 8 9 10 11 120

50

100

150

200

250

300

350

f(x) = 186.182652880832 ln(x) − 178.003657679593

Series2Logarithmic (Series2)

37

Page 38: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Best case:-

2 3 4 5 6 7 8 9 10 11 120

50

100

150

200

250

300

f(x) = 179.606500431743 ln(x) − 171.038985397398

Series2Logarithmic (Series2)

Conclusion:-

Here we conclude that time complexity of merge sort in best, worst, avg. case are same that

is O(logN).

38

Page 39: Algorithm and Computation Complexity

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

Page 40: Algorithm and Computation Complexity

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

Page 41: Algorithm and Computation Complexity

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

count

Best case count

3 9 1

5 9 1

7 13 1

9 13 1

11 13 1

Worst and avg. case count:-

2 3 4 5 6 7 8 9 10 11 120

2

4

6

8

10

12

14f(x) = 0.6 x + 7.2

worst / avg case count

worst / avg case countLinear (worst / avg case count)

41

Page 42: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Best case count:-

0 2 4 6 8 10 120

2

4

6

8

10

12f(x) = NaN x + NaN

Size of arrayBest case countLinear (Best case count)

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

Page 43: Algorithm and Computation Complexity

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

Page 44: Algorithm and Computation Complexity

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

Page 45: Algorithm and Computation Complexity

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

Page 46: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Table:-

Size of array (N) Worst case Avg. case Best case

3 31 22 16

5 64 47 44

7 101 86 82

9 142 101 98

11 187 155 149

Worst case:-

2 3 4 5 6 7 8 9 10 11 120

20

40

60

80

100

120

140

160

180

200

f(x) = 0.499999999999998 x² + 12.5 x − 11.0000000000001

Worst case

Worst casePolynomial (Worst case)

46

Page 47: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Avg. case:-

2 3 4 5 6 7 8 9 10 11 120

20

40

60

80

100

120

140

160

180

f(x) = 95.4767933429504 ln(x) − 94.4145037791329

Avg. case

Avg. caseLogarithmic (Avg. case)

Best case:-

2 3 4 5 6 7 8 9 10 11 120

20

40

60

80

100

120

140

160

f(x) = 95.9645131805802 ln(x) − 99.7166957578352

Best case

Best caseLogarithmic (Best case)

Conclusion:-

Here we conclude that in quick sort time complexity in worst case is O(N 2 ) and in best case

O(logn) and avg. case O(ln N).

47

Page 48: Algorithm and Computation Complexity

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

Page 49: Algorithm and Computation Complexity

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

Page 50: Algorithm and Computation Complexity

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

Page 51: Algorithm and Computation Complexity

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

Page 52: Algorithm and Computation Complexity

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

Page 53: Algorithm and Computation Complexity

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

Page 54: Algorithm and Computation Complexity

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

Page 55: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

Practical 6Design 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 cibe the city with distance di from St. Louis. Here is the pseudo-code.S = ;last = 0for i = 1 to nif (dilast > m)S = S [ fci]glast = ti1Clearly 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 isan 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 s1and 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 optimalsolution S. Then after stopping at the station g at distance di the subproblem P 0 thatremains 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 optimalsolution to P includes within it an optimal solution to P

55

Page 56: Algorithm and Computation Complexity

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

Page 57: Algorithm and Computation Complexity

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

Page 58: Algorithm and Computation Complexity

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

Page 59: Algorithm and Computation Complexity

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

Page 60: Algorithm and Computation Complexity

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

Page 61: Algorithm and Computation Complexity

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)

{

/* base case: If all vertices are assigned a color then

61

Page 62: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

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 */

return false;

}

62

Page 63: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

/* 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

printSolution(color);

return true;

63

Page 64: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

}

/* 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

Page 65: Algorithm and Computation Complexity

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

// t - tuplet vector

// s_size - set size

65

Page 66: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

// 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++ )

{

t[t_size] = s[i];

66

Page 67: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

// 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);

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

return 0;

67

Page 68: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

}

Output:

Practical 11

68

Page 69: Algorithm and Computation Complexity

Algorithm computation and complexity 14PGIT010

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