排序算法--归并排序(python实现)

  • python 代码如下
class sort:
    def mergesort(self,alist):
        if len(alist)<=1:
            return alist
        mid=len(alist)//2
        left=self.mergesort(alist[:mid])
        print("left= "+str(left))
        right=self.mergesort(alist[mid:])
        print("right= "+str(right))
        return self.mergeSortedArray(left,right)
    def mergeSortedArray(self,A,B):
        sortedArray=[]
        l=0
        r=0
        while l

显示结果如下:

left= [6]
right= [5]
left= [5, 6]
left= [3]
right= [1]
right= [1, 3]
left= [1, 3, 5, 6]
left= [8]
right= [7]
left= [7, 8]
left= [2]
right= [4]
right= [2, 4]
right= [2, 4, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

代码写完以后有个错误:

TypeError: slice indices must be integers or None or have an index method

解释:

python对于除法时候可能转换为了浮点数,要将里面的“/”改为“//”就可以运行了

你可能感兴趣的:(排序算法--归并排序(python实现))