#INSERTION SORTING
def ins_sort(n):
alist=[]
for i in range(n):
num=int(input("Enter the number"))
alist.append(num)
count=0
print("Original list is:",alist)
for i in range (1,len(alist)):
key=alist[i]
j=i-1
while j>=0 and key < alist[j]:
alist[j+1]=alist[j]
j=j-1
else:
alist[j+1]=key
count=count+1
print("steps=",i,"list=",alist)
print("list after sorting using insertion sort:",alist)
print("The number of operation while sorting the elements in insertion sort method is=",count)
#main program
n=int(input("Enter the size of insertion sort"))
ins_sort(n)
>>>
= RESTART: C:/Users/Student/AppData/Local/Programs/Python/Python37-32/ins.py =
Input
Enter the size of insertion sort 5
Enter the number 6
Enter the number 5
Enter the number 4
Enter the number 3
Enter the number 1
Original list is: [6, 5, 4, 3, 1]
Output
steps= 1 list= [5, 6, 4, 3, 1]
steps= 2 list= [4, 5, 6, 3, 1]
steps= 3 list= [3, 4, 5, 6, 1]
steps= 4 list= [1, 3, 4, 5, 6]
list after sorting using insertion sort: [1, 3, 4, 5, 6]
The number of operation while sorting the elements in insertion sort method is = 4
#BUBBLE SORTING
def b_s(n):
l=[]
for i in range(n):
num=int(input("enter the number:"))
l.append(num)
count=0
#bubble sort
for k in range(0,n,1):
for j in range(0,n-1,1):
if l[j]>l[j+1]:
t=l[j]
l[j]=l[j+1]
l[j+1]=t
count=count+1
print("Stage=",k+1,"inside list=",j+1,"=",l)
print("Stage=",k+1,"Final list=",l)
print("Final Result list=:",l)
print("The number of operation while sorting the elements in bubble sort method is=",count)
#main program
n=int(input("enter size of list:"))
print("size of list:",n)
b_s(n)
Input
enter size of list:5
size of list: 5
enter the number: 6
enter the number: 5
enter the number: 4
enter the number: 3
enter the number: 1
Output
Stage= 1 inside list= 1 = [5, 6, 4, 3, 1]
Stage= 1 inside list= 2 = [5, 4, 6, 3, 1]
Stage= 1 inside list= 3 = [5, 4, 3, 6, 1]
Stage= 1 inside list= 4 = [5, 4, 3, 1, 6]
Stage= 1 Final list= [5, 4, 3, 1, 6]
Stage= 2 inside list= 1 = [4, 5, 3, 1, 6]
Stage= 2 inside list= 2 = [4, 3, 5, 1, 6]
Stage= 2 inside list= 3 = [4, 3, 1, 5, 6]
Stage= 2 inside list= 4 = [4, 3, 1, 5, 6]
Stage= 2 Final list= [4, 3, 1, 5, 6]
Stage= 3 inside list= 1 = [3, 4, 1, 5, 6]
Stage= 3 inside list= 2 = [3, 1, 4, 5, 6]
Stage= 3 inside list= 3 = [3, 1, 4, 5, 6]
Stage= 3 inside list= 4 = [3, 1, 4, 5, 6]
Stage= 3 Final list= [3, 1, 4, 5, 6]
Stage= 4 inside list= 1 = [1, 3, 4, 5, 6]
Stage= 4 inside list= 2 = [1, 3, 4, 5, 6]
Stage= 4 inside list= 3 = [1, 3, 4, 5, 6]
Stage= 4 inside list= 4 = [1, 3, 4, 5, 6]
Stage= 4 Final list= [1, 3, 4, 5, 6]
Stage= 5 inside list= 1 = [1, 3, 4, 5, 6]
Stage= 5 inside list= 2 = [1, 3, 4, 5, 6]
Stage= 5 inside list= 3 = [1, 3, 4, 5, 6]
Stage= 5 inside list= 4 = [1, 3, 4, 5, 6]
Stage= 5 Final list= [1, 3, 4, 5, 6]
Final Result list=: [1, 3, 4, 5, 6]
The number of operation while sorting the elements in bubble sort method is = 20
No comments:
Post a Comment