0% found this document useful (0 votes)
64 views32 pages

Practical 1: Aim: Implement Factorial Algorithm Using Iterative and Recursive Manner. Code

The document contains code for implementing various sorting algorithms like factorial, bubble sort, insertion sort, and quick sort. It includes code to calculate the best, average, and worst case time complexity of each algorithm. For each algorithm, code is provided to generate sample input arrays and calculate the execution time for different cases. The aim is to analyze and compare the time complexity of these sorting algorithms both theoretically and experimentally.

Uploaded by

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

Practical 1: Aim: Implement Factorial Algorithm Using Iterative and Recursive Manner. Code

The document contains code for implementing various sorting algorithms like factorial, bubble sort, insertion sort, and quick sort. It includes code to calculate the best, average, and worst case time complexity of each algorithm. For each algorithm, code is provided to generate sample input arrays and calculate the execution time for different cases. The aim is to analyze and compare the time complexity of these sorting algorithms both theoretically and experimentally.

Uploaded by

Neem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Enrollment No: 202003103510197

Practical 1

Aim: Implement factorial algorithm using iterative and recursive manner.


Code:
import time
n=int(input("Enter Last Number:\n"))

def iter(n):
fact=1
for i in range(1,n+1):
fact=fact*i

def recursive(n):
if n==0 or n==1:
return 1
else:
return n*recursive(n-1)
print(":::::::::::::Enter a Choice:::::::::::::")
x=int(input("1.For Iterative\n2.For Recursive:"))

if x==1:
a=time.time()
print(a)
iter(n)
b=time.time()
print(b)
print("Time Taken By Iterative Method:",b-a,"seconds")
elif x==2:
a=time.time()
recursive(n)
b=time.time()
print("Time Taken By Recursive Method:",b-a,"seconds")

Output:

CGPIT/CE/SEM-5/DAA 1
Enrollment No: 202003103510197

CGPIT/CE/SEM-5/DAA 2
Enrollment No: 202003103510197

Practical 2

Aim: Implement Bubble sort algorithm and perform its best case, average case
and worst Case analysis.

General Case:

Code:
from time import time
def bubblesort(elements):
a=time()*1000
swapped = False
for n in range(len(elements)-1, 0, -1):
for i in range(n):
if elements[i] > elements[i + 1]:
swapped = True
elements[i], elements[i + 1] = elements[i + 1], elements[i]
b=time()*1000
print("Time Taken To Swap:",b-a,"Ms")
n=int(input("Enter total no of element:"))
elements=[]
for i in range(n):
x=int(input("Enter a number:"))
elements.append(x)
print("Unsorted list is,")
print(elements)
bubblesort(elements)
print("Sorted Array is, ")
print(elements)
Output:

CGPIT/CE/SEM-5/DAA 3
Enrollment No: 202003103510197

Best Case:
from time import time
def bubblesort(elements):
a=time()*1000
swapped = False
for n in range(len(elements)-1,0,-1):
for i in range(n):
if elements[i] > elements[i+1]:
swapped = True
elements[i], elements[i + 1] = elements[i + 1], elements[i]
b=time()*1000
print("Time Taken To Swap:",b-a,"Ms")
n=int(input("Enter total no of element:"))
elements=[]
for i in range(n):
x=int(input("Enter a number:"))
elements.append(x)
elements.sort()
print("Unsorted list is,")
print(elements)
bubblesort(elements)
print("Sorted Array is, ")
print(elements)

Output:

CGPIT/CE/SEM-5/DAA 4
Enrollment No: 202003103510197

Average Case:

Code:

from time import time


def bubblesort(elements):
a=time()*1000
swapped = False
for n in range(len(elements)-1,0,-1):
for i in range(n):
if elements[i] > elements[i+1]:
swapped = True
elements[i], elements[i + 1] = elements[i + 1], elements[i]
b=time()*1000
print("Time Taken To Swap:",b-a,"Ms")
n=int(input("Enter total no of element:"))
elements=[]
for i in range(n):
x=int(input("Enter a number:"))
elements.append(x)
print("Unsorted list is,")
print(elements)
bubblesort(elements)
print("Sorted Array is, ")
print(elements)

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 7


Enrollment No: 202003103510197

WorstCase:

Code:
from time import time
def bubblesort(elements):
a=time()*1000
swapped = False
for n in range(len(elements)-1,0,-1):
for i in range(n):
if elements[i] > elements[i+1]:
swapped = True
elements[i], elements[i + 1] = elements[i + 1], elements[i]
b=time()*1000
print("Time Taken To Swap:",b-a,"Ms")
n=int(input("Enter total no of element:"))
elements=[]
for i in range(n):
x=int(input("Enter a number:"))
elements.append(x)
elements.sort(reverse=True)
print("Unsorted list is,")
print(elements)
bubblesort(elements)
print("Sorted Array is, ")
print(elements)

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 8


Enrollment No: 202003103510197

Practical 3

Aim: Implement insertion sort algorithm and perform its best case, average
case and worst case analysis.
Code:
#insertion Sort Algorithm.
 # GENERAL CASE
import time
c1,c2=0,0
n=int(input("Enter How many Data You Want:"))
arr=[int(input("Enter Value :")) for i in range(n)]
start=time.time()
for j in range(1,len(arr)):
    c1+=1
    key=arr[j]
    i=j-1
while (i>-1 and arr[i]>key):
    c2+=1
    arr[i+1]=arr[i]
    i-=1
    arr[i+1]=key
    end=time.time()
    print("\nSorted List is:",arr)
print("For Loop Executed {} Times.".format(c1))
print("while Loop Executed {} Times.".format(c2))
print("\nExecution Time:{}".format(round((end-start)*1000,5))+" ms")

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 9


Enrollment No: 202003103510197

Code:
#Best Case
import time
from time import time
c1,c2=0,0
l=[i for i in range(1,10001)]
start=time()
for j in range(1,len(l)):
c1+=1
key=l[j]
i=j-1
while (i>-1 and l[i]>key):
c2+=1
l[i+1]=l[i]
i-=1
l[i+1]=key
end=time()
print("For Loop Executed {} Times.".format(c1))
print("while Loop Executed {} Times.".format(c2))
print("\nExecution Time:{}".format(round((end-start)*1000,5))+" ms")
Output:

Code:
#AVERAGE CASE
import time
import random
c1,c2=0,0
l=[random.randint(1,10000) for i in range(1,10001)]
start=time.time()
for j in range(1,len(l)):
    c1+=1
    key=l[j]
    i=j-1
while (i>-1 and l[i]>key):
    c2+=1
    l[i+1]=l[i]
    i-=1
    l[i+1]=key
    end=time.time()
print("For Loop Executed {} Times.".format(c1))

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 10


Enrollment No: 202003103510197

print("while Loop Executed {} Times.".format(c2))


print("\nExecution Time:{}".format(round((end-start)*1000,5))+" ms")

Output:

Code:
# WORST CASE
import time
c1,c2=0,0
print("-----Worst Case  ")
l=[i for i in reversed(range(1,10001))]
start=time.time()
for j in range(1,len(l)):
    c1+=1
    key=l[j]
    i=j-1
while (i>-1 and l[i]>key):
    c2+=1
    l[i+1]=l[i]
    i-=1
    l[i+1]=key
    end=time.time()
print("For Loop Executed {} Times.".format(c1))
print("while Loop Executed {} Times.".format(c2))
print("\nExecution Time:{}".format(round((end-start)*1000,5))+" ms")

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 11


Enrollment No: 202003103510197

Practical 4

Aim: Implement quick sort algorithm and perform its best case, average
case and worst case analysis.
Code:
#Quick Sort Algorithm
import time
l=[int(input("Enter Element:")) for i in range(int((input("Enter how many element you
want:"))))]
p=0
r=len(l)-1
def quicksort(l,p,r):
if p<r:
q=partition(l,p,r)
quicksort(l,p,q-1)
quicksort(l,q+1,r)
return l
def partition(l,p,r):
x=l[r]
i=p-1
for j in range(p,r):
if l[j]<=x:
i+=1
l[i],l[j]=l[j],l[i]
l[i+1],l[r]=l[r],l[i+1]
return i+1
start=time.time()
print("Sorted list:",quicksort(l,p,r))
end=time.time()
print("Execution Time:",round((end-start)*1000,5),"ms")

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 12


Enrollment No: 202003103510197

Best Case:
#Quick Sort Algorithm
import time
import random
l=[random.randint(1,10000) for i in range(1,10001)]
p=0
r=len(l)-1
def quicksort(l,p,r):
if p<r:
q=partition(l,p,r)
quicksort(l,p,q-1)
quicksort(l,q+1,r)
return l
def partition(l,p,r):
x=l[r]
i=p-1
for j in range(p,r):
if l[j]<=x:
i+=1
l[i],l[j]=l[j],l[i]
l[i+1],l[r]=l[r],l[i+1]
return i+1
start=time.time()
quicksort(l,p,r)
end=time.time()
print("Execution Time:",round((end-start)*1000,5),"ms")

Output:

Average Case:
#Quick Sort Algorithm
import time
import sys
sys.setrecursionlimit(15000)
l=[i for i in reversed(range(1,10001))]
p=0
r=len(l)-1
def quicksort(l,p,r):
if p<r:
CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 13
q=partition(l,p,r)
quicksort(l,p,q-1)
Enrollment No: 202003103510197

quicksort(l,q+1,r)
return l
def partition(l,p,r):
x=l[r]
i=p-1
for j in range(p,r):
if l[j]<=x:
i+=1
l[i],l[j]=l[j],l[i]
l[i+1],l[r]=l[r],l[i+1]
return i+1
start=time.time()
quicksort(l,p,r)
end=time.time()
print("Execution Completed:")
print("Execution Time:",round((end-start)*1000,5),"ms")

Output:

Worst Case:
#Quick Sort Algorithm
import time
import sys
sys.setrecursionlimit(15000)
l=[i for i in range(1,10001)]
p=0
r=len(l)-1
def quicksort(l,p,r):
if p<r:
q=partition(l,p,r)
quicksort(l,p,q-1)
quicksort(l,q+1,r)
return l
def partition(l,p,r):
x=l[r]
i=p-1
for j in range(p,r):
if l[j]<=x:
i+=1
l[i],l[j]=l[j],l[i]
l[i+1],l[r]=l[r],l[i+1]
CGPIT/CE/SEM-5/ Design
return i+1& Analysis of Algorithms 14
start=time.time()
Enrollment No: 202003103510197

quicksort(l,p,r)
end=time.time()
print("Execution Time:",round((end-start)*1000,5),"ms")
Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 15


Enrollment No: 202003103510197

Practical 5

Aim: Implement knapsack problem using greedy approach.


Code:
import time
n = int(input("How many Data You Want:"))
print("\n\t-----Profit Data-----")
profit = [int(input("Enter Profit: ")) for i in range(n)]
print("\n\t-----Weight Data-----")
weight = [int(input("Enter weight: ")) for i in range(n)]
print("\n\t-----TOtal Weight-----")
TW = int(input("Enter Total weight:"))
index=[i for i in range(1,len(profit)+1)]
ratio = []
for k in range(n):
l = profit[k]/weight[k]
ratio.append(l)

print("\nTable Before Execution:")


print("\nObject\tProfit\tWeight\tRatio")
print("-------------------------------\n")
for i in range(len(profit)):
print(index[i],end="\t")
print(profit[i],end="\t")
print(weight[i],end="\t")
print(ratio[i],end="\n")
print("-------------------------------\n")

def knapsack(v,w,TW):
xi = []
for i in range(len(v)):
xi.append(0)
weight = 0
for i in range(len(v)):
if weight+w[i] <= TW:
xi[i] = 1
weight = weight+w[i]
else:
xi[i] = (TW-weight)/w[i]
weight = w
break
return xi

c=int(input("Enter Choice\n1)Max Profit\n2)Min Weight\n3)P/w Ratio\nChoice:"))


if c==1:
for i in range(len(profit)-1):
CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 16
for j in range(len(profit)-i-1):
if profit[j]<profit[j+1]:
Enrollment No: 202003103510197

profit[j], profit[j+1] = profit[j+1], profit[j]


ratio[j], ratio[j+1] = ratio[j+1], ratio[j]
weight[j], weight[j+1] = weight[j+1], weight[j]
index[j],index[j+1]=index[j+1],index[j]
elif c==2:
for i in range(len(weight)-1):
for j in range(len(weight)-i-1):
if weight[j]>weight[j+1]:
weight[j], weight[j+1] = weight[j+1], weight[j]
profit[j], profit[j+1] = profit[j+1], profit[j]
ratio[j], ratio[j+1] = ratio[j+1], ratio[j]
index[j],index[j+1]=index[j+1],index[j]
elif c==3:
for i in range(len(ratio)-1):
for j in range(len(ratio)-i-1):
if ratio[j] < ratio[j+1]:
ratio[j], ratio[j+1] = ratio[j+1], ratio[j]
profit[j], profit[j+1] = profit[j+1], profit[j]
weight[j], weight[j+1] = weight[j+1], weight[j]
index[j],index[j+1]=index[j+1],index[j]
else:
print("Enter Valid Choice!!!")
start=time.time()
x=knapsack(profit,weight,TW)
end=time.time()
Tprofit=0

print("\nTable After Execution:")


print("\nObject\tProfit\tWeight\tXi\tUsed Weight")
print("-------------------------------------------\n")
for i in range(len(profit)):
print(index[i],end="\t")
print(profit[i],end="\t")
print(weight[i],end="\t")
print(round(x[i],2),end="\t")
print(x[i]*weight[i])
Tprofit+=x[i]*profit[i]
print("-------------------------------------------\n")
print("Total time for Execution:",round((end-start)*1000,5),"ms")
print("Total Profit Gain:",Tprofit)

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 17


Enrollment No: 202003103510197

Output:
1. Max Profit:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 18


Enrollment No: 202003103510197

2. Max Profit:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 19


Enrollment No: 202003103510197

3. P/W Ratio:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 20


Enrollment No: 202003103510197

Practical 6

Aim: Implement Activity Selection problem using greedy approach.


Code:
#include<stdio.h>
void main()
{
int i,j,a,b,f,n,min,temp,vnode=1,tcost=0;
int c[100][100],root[100];
printf("1)Number\n2)Alphabet");
printf("\n\nEnter Your choice:");
scanf("%d",&temp);
if(temp==1)
f=1;
if(temp==2)
f=65;
printf("\nEnter Number of Node:");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(f==1)
printf("Enter cost of edje[%d][%d]:",i+f,j+f);
if(f==65)
printf("Enter cost of edje[%c][%c]:",i+f,j+f);
scanf("%d",&c[i][j]);
c[j][i]=c[i][j];
if(c[i][j]==0) c[i]
[j]=c[j][i]=999;
}
printf("\nEnter Starting Node(Number):");
scanf("%d",&temp);
root[temp-1]=1;
while(vnode<n)
{
min=999;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(c[i][j]<min)
if(root[i]!=0)
{
min=c[i][j];
CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 21
Enrollment No: 202003103510197

a=i;
b=j;
}
if(root[a]==0 || root[b]==0)
{
if(f==1)
printf("\nNode %d to %d Cost is:%d",a+f,b+f,min);
if(f==65)
printf("\nNode %c to %c Cost is:%d",a+f,b+f,min);
tcost+=min;
root[b]=1;
vnode++;
}
c[a][b]=c[b][a]=999;
}
printf("\n\nMinimum Cost=%d\n",tcost);
}
Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 22


Enrollment No: 202003103510197

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 23


Enrollment No: 202003103510197

Practical 7

Aim: Implement making change problem using dynamic programming.


Code:
#include<stdio.h>
void main()
{
int i,j,n,N,x,y;
int c[100][100],d[100],m[100];
printf("Enter Number of Coins:");
scanf("%d",&n);
printf("\n");
for(i=1;i<=n;i++)
{
printf("Enter value of %d Coins:",i);
scanf("%d",&d[i]);
}
printf("\nEnter Amount:");
scanf("%d",&N);
printf("\n\n ");
for(j=0;j<=N;j++)
printf("\t %d",j);
printf("\n");
for(i=1;i<=n;i++)
{
printf("\nd%d %d",i,d[i]);
for(j=0;j<=N;j++)
if(j==0)
{
printf("\t 0");
c[i][j]=0;
}
else if(i==1 && j<d[i])
{
printf("\tINF");
c[i][j]=999;
}
else if(i==1)
{
c[i][j]=1+c[1][j-d[i]];
if(c[i][j]<999)
printf("\t %d",c[i][j]);
else& Analysis of Algorithms
CGPIT/CE/SEM-5/ Design 24
Enrollment No: 202003103510197

printf("\tINF");
}
else if(j<d[i])
{
c[i][j]=c[i-1][j];
if(c[i][j]<999)
printf("\t %d",c[i][j]);
else
printf("\tINF");
}
else
{
if(c[i-1][j]<(1+c[i][j-d[i]]))
c[i][j]=c[i-1][j];
else
c[i][j]=1+c[i][j-d[i]];
if(c[i][j]<999)
printf("\t %d",c[i][j]);
else
printf("\tINF");
}
}
printf("\n\nNumber of coins Required:%d",c[n][N]);
x=n;y=N;
while(c[x][y]!=0)
{
while(c[x][y]==c[x-1][y])
x--;
y=y-d[x];
m[x]+=1;
}
for(i=1;i<=n;i++)
if(m[i]!=0)
printf("\n%d coins of %d.",m[i],d[i]);
printf("\n");
}

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 25


Enrollment No: 202003103510197

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 26


Enrollment No: 202003103510197

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 27


Enrollment No: 202003103510197

Practical 8

Aim: Implement Longest common subsequence using dynamic programming.


Code:
#include<stdio.h>
#include<string.h>
void main()
{
int i,j,k=0;
int c[100][100];
char a[100],b[100],lcs[100];
printf("Enter First String:");
scanf("%s",b);
printf("Enter Second String:");
scanf("%s",a);
printf("\n\n\t \t");
for(i=0;i<strlen(b);i++)
printf("\t%c",b[i]);
for(i=0;i<=strlen(a);i++)
{
if(i==0)
printf("\n\t ");
else
printf("\n\t%c",a[i-1]);
for(j=0;j<=strlen(b);j++)
{
if(i==0 || j==0)
{
c[i][j]=0; printf("\t
%d",c[i][j]);
}
else if(a[i-1]==b[j-1])
{
c[i][j]=1+c[i-1][j-1];
printf("\t%d",c[i][j]);
}
else
{
if(c[i][j-1]>c[i-1][j])
c[i][j]=c[i][j-1];
else
c[i][j]=c[i-1][j];
printf("\t%d",c[i][j]);
}
CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 28
Enrollment No: 202003103510197

}
}
printf("\n\nLongest common subsequence:");
i=strlen(a);
j=strlen(b);
while(i>0 && j>0)
if(a[i-1]==b[j-1])
{
lcs[k]=a[i-1];
i--;j--;k++;
}
else if(c[i-1][j]>c[i][j-1])
{ i--; }
else
{ j--; }
for(i=strlen(lcs)-1;i>=0;i--)
printf("%c",lcs[i]);
printf("\n");
}

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 29


Enrollment No: 202003103510197

Practical 9

Aim: Implement topological sorting algorithm and measure its execution time.
Code:
#include<stdio.h>
#include<string.h>
#include<time.h>
void main()
{
clock_t st,et;
int i,j,k,f,n,m,x=1,lc=0;
char s[100],p[100];
double tt;
printf("Enter String:");
scanf("%s",s);
printf("Enter Pattern:");
scanf("%s",p);
st=clock();
n=strlen(s);
m=strlen(p);
for(i=0;lc++,i<=n-m;i++)
{
f=0;
k=i; for(j=0;lc++,j<m;j+
+,k++) if(s[k]==p[j])
f++;
else
break;
if(f==m)
{
printf("\nPattern Match At %d.",i+1);
x=0;
}
}
if(x)
printf("\nNo Match Found.");
et=clock();
tt=(double) (et-st)/CLOCKS_PER_SEC;
printf("\n\nTotal Time:%.25lf Second.",tt);
printf("\nTotal Loop:%d.\n",lc);
}

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 30


Enrollment No: 202003103510197

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 31


Enrollment No: 202003103510197

Practical 10

Aim: Implement a program that can traverse a path using depth first search
algorithm.
Code:
#include<stdio.h>
int a[100][100],r[100],s[100],n,f,k=0;
int check(int x)
{
int i;
for(i=0;i<k;i++)
if(s[i]==x)
{
x=0;
i=k+1;
}
return x;
}
void dfs(int node)
{
int i;
r[node]=1;
for(i=0;i<n;i++)
if(a[node][i] && !(r[i]))
{
if(f==1)
printf("\n\t %d --> %d",node+f,i+f);
else
printf("\n\t %c --> %c",node+f,i+f);
s[k]=check(node+f);
k++;
s[k]=check(i+f);
k++;
dfs(i);
}
}
void main()
{
int i,j,c=0,temp;
printf("1)Number\n2)Alphabet");
printf("\n\nEnter Your choice:");
scanf("%d",&temp);
if(temp==1)
f=1;
CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 32
Enrollment No: 202003103510197

if(temp==2)
f=65;
printf("\nEnter Number of Node:");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(f==1)
printf("Edge between Node[%d][%d]:",i+f,j+f);
else
printf("Edge between Node[%c][%c]:",i+f,j+f);
scanf("%d",&a[i][j]);
}
printf("\n***** Selected Edge *****");
dfs(0);
for(i=0;i<n;i++)
if(r[i])
c++;
printf("\n\n\t");
for(i=0;i<k;i++)
if(s[i]!=0)
if(f==1)
printf("%d ",s[i]);
else
printf("%c ",s[i]);
if(c!=n)
printf("\nGrap is Not Connected.");
printf("\n");
}

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 33


Enrollment No: 202003103510197

Output:

CGPIT/CE/SEM-5/ Design & Analysis of Algorithms 34

You might also like