Home  >  Article  >  Backend Development  >  Python选择排序、冒泡排序、合并排序代码实例

Python选择排序、冒泡排序、合并排序代码实例

WBOY
WBOYOriginal
2016-06-10 15:15:351432browse

前两天刚装了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             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         if left[i]             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)         return L
    else:
        middle = int(len(L)/2)
        left = mergesort(L[:middle])
        right = mergesort(L[middle:])
        return merge(left, right)


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn