[英]mergesort tree implementation in python
n=4
arr=[1,2,3,4]
tree=[[] for i in range(2*n-1)]
def build_tree(idx,l,r):
if l==r:
tree[idx].append(arr[l])
else:
mid=(l+r)//2
build_tree(2*idx,l,mid)
build_tree(2*idx+1,mid+1,r)
tree[idx]=merge(tree[2*idx],tree[2*idx+1])
def merge(left,right):
myList=[]
i=0
j=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
myList.append(left[i])
i += 1
else:
myList.append(right[j])
j += 1
while i < len(left):
myList.append(left[i])
i += 1
while j < len(right):
myList.append(right[j])
j += 1
return myList
if __name__ == '__main__':
build_tree(0,0,n-1)
print(tree)
我在 python https://discuss.codechef.com/t/merge-sort-tree-tutorial/14277中實現合並排序樹。 .當我打印樹時,我正在關注 output
[[1, 2, 3, 4], [3, 4], [3], [4], [], [], []] 這是錯誤的。
但是缺少諸如 [1] 和 [2] 之類的一些值。我沒有錯在哪里。互聯網上沒有 python 實現可用於合並排序樹。請幫助我更正它,或者如果可能,請提供另一種實現在 python 中。
您在遞歸步驟中執行的索引數學是錯誤的,因此只出現樹的右半部分。 這個問題與零索引有關。 如果根為零,則左分支需要為1
,右分支需要為2
。 您的代碼生成0
和1
,因此一半的樹消失了。
嘗試:
else:
mid=(l+r)//2
build_tree(2*idx+1,l,mid) # +1 for idx argument here
build_tree(2*idx+2,mid+1,r) # +2 instead of +1 here
tree[idx]=merge(tree[2*idx+1],tree[2*idx+2]) # also update the indexes used here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.