选择,冒泡,合并 via 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)

posted on 2009-09-27 21:56  J.D Huang  阅读(...)  评论(... 编辑 收藏

统计