Sorting Algos in Python
'''Date- 6th November 2022 '''
''' Some Sorting Algorithms in Python '''
def bubbleSort(l):
n=len(l)
for i in range(n-1):
for j in range(0,n-1-i):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
print(l)
def selectionSort(l):
n=len(l)
for i in range(n-1):
minInd=i
for j in range(i+1,n):
if l[j]<l[minInd]:
minInd=j
l[minInd],l[i]=l[i],l[minInd]
print(l)
def insertionSort(l):
n=len(l)
for i in range(n-1):
key=l[i+1]
j=i
while l[j]>key and j>=0:
l[j+1]=l[j]
j-=1
l[j+1]=key
print(l)
def mergeSort(l):
if len(l)>1:
m=len(l)//2
L=mergeSort(l[:m])
R=mergeSort(l[m:])
i,j,k=0,0,0
while(i<len(L) and j<len(R)):
if(L[i]<R[j]):
l[k]=L[i]
k+=1
i+=1
else:
l[k]=R[j]
j+=1
k+=1
while(i<len(L)):
l[k]=L[i]
i+=1
k+=1
while(j<len(R)):
l[k]=R[j]
j+=1
k+=1
return l
def countSort(ls):
n=len(ls)
m=max(ls)
itr=0
temp=[0]*(m+1)
for elem in ls:
temp[elem]+=1
print(temp)
for i in range(m+1):
while temp[i]!=0:
ls[itr]=i
itr+=1
temp[i]-=1
# print(ls)
def partition(ls,l,r):
pivot=ls[r]
i=l-1
for j in range(l,r):
if ls[j]<pivot:
i+=1
ls[i],ls[j]=ls[j],ls[i]
ls[i+1],ls[r]=ls[r],ls[i+1]
return i+1
def quickSort(ls,l,r):
if l<r:
pi=partition(ls,l,r)
quickSort(ls,l,pi-1)
quickSort(ls,pi+1,r)
def main():
countSort([5,1,3,5,4,4,2,5,7,8,9])
print("Hello!")
if __name__=="__main__":
main()
Comments
Post a Comment