不明白为啥Java版本的归并排序非得要传递那么多的参数,python版本的很简单啊,如果有什么错误,肯请小伙伴指出来
def merge_sort(alist):
if len(alist) <= 1:
return alist
num = len(alist) // 2
left = merge_sort(alist[:num])
right = merge_sort(alist[num:])
return merge(left, right)
def merge(left, right):
l, r = 0, 0
result = []
while l < len(left) and r < len(right):
if left[l] < right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
result += left[l:]
result += right[r:]
return result
测试速度:
from random import shuffle
import time
N = 100000
li = list(range(N))
shuffle(li)
t1 = time.time()
res = merge_sort(li)
t2 = time.time()
print("归并排序消耗时间:", t2 - t1)
结果:
归并排序消耗时间: 1.0948657989501953
如此看来,这个速度好像和希尔排序差不多