【Python】用python实现归并排序算法

先放上代码,有空再整理思路

def merge(left,right):

    temp_ans=[]
 #   temp_index=0
    i,j=0,0
    while iand jif(left[i]1
        else:
            temp_ans.append(right[j])
            j+=1
 #        temp_index+=1
    if(i>=len(left)):
        temp_ans.extend(right[j:])
    if(j>=len(right)):
        temp_ans.extend(left[i:])
    temp_ans
    return temp_ans  


def merge_sort(alist):

    if(len(alist)<=1):
        return alist
    else:
        low=0
        high=len(alist)
        print(alist)
        mid=(low+high)//2
        l=alist[low:mid]
        r=alist[mid:high]
        left=merge_sort(l)
        right=merge_sort(r)
        return merge(left,right)

alist=[69,3,2,45,67,3,2,4,45,63,24,233]
print(merge_sort(alist))

你可能感兴趣的:(Python,计算机算法设计与分析)