1. 程式人生 > >python--歸併排序實現

python--歸併排序實現

對於一個想找工作的人來說,歸併排序必須能手寫出來。

歸併排序原理無需解釋,直接給出python程式碼:

def mergesort(num):
    if(len(num)==1):return num
    mid=len(num)//2
    left=mergesort(num[:mid])
    right=mergesort(num[mid:])
    return merge(left,right)

def merge(left,right):
    i,j=0,0
    result=[]
    while i<len(left) and j<len(right):
        if(left[i]<right[j]):
            result.append(left[i])
            i+=1
        else:
            result.append(right[j])
            j+=1
    if(i<len(left)):
        while(i<len(left)):
            result.append(left[i])
            i+=1
    if (j < len(right)):
        while (j < len(right)):
            result.append(right[j])
            j += 1
    return result






pai = [5, 12, 79, 2, 4, 8, 6]
paixu=mergesort(pai)
print(paixu)