from timeit import Timer
def back_sort(lis):
n= len(lis)
if n == 1:
return (lis)
mid = n//2
left_sorted = back_sort(lis[:mid])
right_sorted = back_sort(lis[mid:])
n_left = len(left_sorted)
n_right = len(right_sorted)
left_start = 0
right_start = 0
merged_lis = []
while left_start < n_left and right_start <n_right:
if left_sorted[left_start] <= right_sorted[right_start]:
merged_lis.append(left_sorted[left_start])
left_start += 1
else:
merged_lis.append(right_sorted[right_start])
right_start += 1
merged_lis += left_sorted[left_start:]
merged_lis += right_sorted[right_start:]
return merged_lis
def merge_sort(lis,start,end):
if start == end:
return [lis[start]]
mid = (start+end)//2
right_sorted = merge_sort(lis,mid+1,end)
left_sorted = merge_sort(lis,start,mid)
n_left = len(left_sorted)
n_right = len(right_sorted)
left_start = 0
right_start = 0
merged_lis = []
while left_start < n_left and right_start <n_right:
if left_sorted[left_start] <= right_sorted[right_start]:
merged_lis.append(left_sorted[left_start])
left_start += 1
else:
merged_lis.append(right_sorted[right_start])
right_start += 1
merged_lis += left_sorted[left_start:]
merged_lis += right_sorted[right_start:]
#print(merged_lis)
return merged_lis
if __name__ == "__main__":
lis = [49,38,65,97,76,13,27,49]
n = len(lis)-1
print(back_sort(lis))
print(merge_sort(lis,0,n))
t1 = Timer('back_sort(lis)', 'from __main__ import back_sort')
t2 = Timer('merge_sort(lis,0,n)', 'from __main__ import merge_sort')
print(t1.timeit(number=1000))
print(t2.timeit(number=1000))
为什么会提示lis未定义呢?
请大神指点!