Professional Documents
Culture Documents
DAA Lab Experiment 1
DAA Lab Experiment 1
Experiment 1
Design and Analysis of Algorithms Lab
20CP209P
AIM: To perform insertion sort on an array of integers and analyse it’s time complexity.
THEORY:
In this sorting method, each element from 0 th is compared to all the elements before it in the
array from (i-1)th to 0th and once it becomes larger than the element it is being compared to,
we delete it from it’s current position and insert it after this element. This is done with all the
elements from 1st to nth.
Thus, the array is sorted incrementally as we move through it.
ALGORITHM:
1
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 1
OUTPUT:
2
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 1
ANALYSIS:
no. of steps in worst case: (reversely sorted)
=3+n+1+n+n+3(n-1)+n-1+(n(n+1)/2)-1+(n(n-1)/2)+1
=3+4n+3n-3+n2/2+n/2+n2/2-n/2
=n^2+7n =O(n^2)
AIM: To perform selection sort on an array of integers and analyse it’s time complexity.
THEORY:
Here, we find the minimum element in the array, switch with the 0 th position element and
change the current working array to 1st – (n-1)th elements and we continue doing this until the
length of current array is 1.
Here also, we are sorting the array in increasing parts with every iteration (from left to right).
ALGORITHM:
3
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 1
CODE:
#selection sort
n=int(input('enter length of array'))
l=[0]*n
print("enter ",n," elements:")
for i in range(n):
l[i]=int(input())
for i in range(n-1):
m=l[i]
k=i
for j in range(i+1,n):
if l[j]<m:
m=l[j]
k=j
l[k]=l[i]
l[i]=m
print(l)
4
REHA SHAH 21BCP148 G5 DAA LAB EXPERIMENT 1
OUTPUT:
ANALYSIS:
no. of steps in worst case: (reversely sorted)
=1+1+1+n+1+n+n+4(n-1)+n(n+1)/2+3(n-1)n/2+1
=5+3n+4n-4+2n^2-n
=2n^2+6n+1 =O(n^2)