Python选择排序、冒泡排序、合并排序代码实例
前两天刚装了python 3.1.1, 禁不住技痒写点code。
1.选择排序
>>> def SelSort(L):
length=len(L)
for i in range(length-1):
minIdx=i
minVal=L[i]
j=i+1
while j<length:
if minVal>L[j]:
minIdx=j
minVal=L[j]
j=j+1
L[i],L[minIdx]=L[minIdx],L[i]
return L
2.冒泡排序
>>> def bubSort(L):
swapped=True
while swapped:
swapped=False
for i in range(len(L)-1):
if L[i]>L[i+1]:
L[i],L[i+1]=L[i+1],L[i]
swapped=True
return L
3.合并排序
>>> def merge(left,right):
result=[]
i,j=0,0
while i<len(left) and j<len(right):
if left[i]<=right[j]:
result.append(left[i])
i=i+1
else:
result.append(right[j])
j=j+1
result+=left[i:]
result+=right[j:]
return result
>>> def mergesort(L):
if len(L) < 2:
return L
else:
middle = int(len(L)/2)
left = mergesort(L[:middle])
right = mergesort(L[middle:])
return merge(left, right)