我已经使用Sedgewick在他的课程中讲授的算法在Python中编写了Mergesort的实现。我无法正确排序。代码有什么问题?
def merge(a, aux, lo, mid, hi):
assert isSorted(a, lo, mid)
assert isSorted(a, mid+1, hi)
for k in range(lo, hi):
aux[k] = a[k]
i = lo
j = mid + 1
for k in range(lo, hi):
if i > mid:
a[k] = aux[j]
j += 1
elif j > hi:
a[k] = aux[i]
i += 1
elif a[i] < a[j]:
a[k] = aux[i]
i += 1
else:
a[k] = aux[j]
j += 1
assert isSorted(a, lo, hi)
def sort(a, aux, lo, hi):
if (lo >= hi): return a
mid = math.floor(lo + (hi-lo) / 2)
sort(a, aux, lo, mid)
sort(a, aux, mid+1, hi)
merge(a, aux, lo, mid, hi)
def merge_sort(a):
aux = [0] * len(a)
sort(a, aux, 0, len(a))
assert isSortedArray(a)
答案 0 :(得分:0)
Python使用基于0的索引。你需要调整你的lo,mid,hi到0的索引。
起点是
sort(a,aux,0, len(a)-1)