python四种简单排序

时间:2022-09-19 06:10:44
  #!/usr/bin/python
#排序方法
#冒泡排序
def buble(l):    
for i in range(len(l)):
for j in range(len(l)-i-1):
if l[j]>l[j+1]:
l[j+1],l[j]=l[j],l[j+1]
print l
#选择排序
def select(l):
for i in range(len(l)):
for j in range(i+1,len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
print l
#插入排序
def insert(l):
for i in range(1,len(l)):
s=l[i]
j=i while j>0 and l[j-1]>s:
l[j]=l[j-1]
j-=1
l[j]=s
print l
#快速排序
def fastsort(l,a,b):
if a<b:
i,j = a,b
x=l[a]
while a<b:
while a<b and l[b]>=x:
b-=1
l[a]=l[b]
while a<b and l[a]<x:
a+=1
l[b]=l[a]
l[b]=x
fastsort(l,i,a-1)
fastsort(l,a+1,j)
return l
buble([2,5,6,3,8,4,7,9])
select([2,5,6,3,8,4,7,9])
insert([2,5,6,3,8,4,7,9])
l=fastsort([6,2,7,5,8,3,9],0,6)
print "h",l