Python Bubble Sort and Recursive Functions
Bubble Sort in Python
l=[30,12,18,8]
n=len(l)
for i in range (0,n-1):
for j in range (0,n-i-1):
if l[j]>l[j+1]:
temp=l[j]
l[j]=l[j+1]
l[j+1]=temp
print(l)
Output
Insertion Sort using Python
li=[3,2,5,1]
l=len(li)
# finding minimum
minimum=li[0]
for i in range (1,l):
if li[i]<minimum:
minimum=li[i]
temp=li[0]
li[0]=li[i]
li[i]=temp
#inserting the values
for i in range (2,l):
x=li[i]
#searching the list from position 1 to position i
for j in range(1,i):
if x<li[j]:
pos=j
for k in range (i,j,-1):
li[k]=li[k-1]
li[pos]=x
break
print(li)
Output
Selection Sort using Python
l=[30,8,12,18,4,5]
n=len(l)
for k in range (0,n-1):
minimum = l[k]
pos=k
for i in range (k+1,n):
if l[i] < minimum:
minimum=l[i]
p=i
temp=l[pos]
l[pos]=l[p]
l[p]=temp
print(l)
Output
Finding factorial using Recursion
def fact(num):
if num==1:
return 1
else:
return num * fact(num-1)
k=fact(5)
print(k)
Output
Finding the minimum number
l=[30,8,12,18]
n=len(l)
for k in range (0,n-1):
minimum = l[k]
pos=k
for i in range (k+1,n):
if l[i] < minimum:
minimum=l[i]
p=i
temp=l[pos]
l[pos]=l[p]
l[p]=temp
print(l)
Output