- 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<len(A) and r<len(B):
if A[l]<B[r]:
sortedArray.append(A[l])
l+=1
else:
sortedArray.append(B[r])
r+=1
sortedArray+=A[l:]
sortedArray+=B[r:]
return sortedArray
unsortedArray=[6, 5, 3, 1, 8, 7, 2, 4]
merge_sort=sort()
print(merge_sort.mergesort(unsortedArray))
显示结果如下:
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对于除法时候可能转换为了浮点数,要将里面的“/”改为“//”就可以运行了