python | 桶排序、冒泡排序、选择排序、去重
桶排序(简化版)
O(M+N)
a = [5,6,9,2,3,5,4,7,2,1,0,6]
t=[] # 初始化t(桶)
for i in range(10):
t.append(0)
for item in a:
t[item]+=1 # 改为 t[item]=1 去重再排序
n=0
b=[]
for item in t:
for k in range(item):
b.append(n)
n+=1
print(b)
冒泡排序
O(N^2)
a = [5,6,9,2,3,5,4,7,2,1,0,6]
m=len(a)-1
n=m
while n>0:
j=0
while j<n:
if a[j]>a[j+1]:
t=a[j]
a[j]=a[j+1]
a[j+1]=t
j+=1
n-=1
a
选择排序
最慢 O(N^2) 平均 O(NlogN)
a = [5,6,9,2,3,5,4,7,2,1,0,6]
def quicksort(left,right):
if left>right:
return
temp=a[left] # temp = left 不对 Why?
j=right
i=left
while i!=j:
while a[j]>=temp and i<j:
j-=1
while a[i]<=temp and i<j:
i+=1
if i<j:
t=a[j]
a[j]=a[i]
a[i]=t
a[left]=a[j]
a[j]=temp # Because 此处若为 a[j]=a[temp] 则 由于temp==left 交换失去效果 a[j]==a[left]==a[temp]
quicksort(left,j-1)
quicksort(j+1,right)
quicksort(0,len(a)-1)
print(a)
排序后去重
a = [5,6,9,2,3,5,4,7,2,1,0,6]
a.sort()
print(a)
c=[a[0],]
for i in range(1,len(a)): #错位比较,不同输出,相同表示与前一项值相同则不输出
if a[i]!=a[i-1]:
c.append(a[i])
print(c)