我的下面的 python 合并排序代码有什么问题吗?
合并排序
它显示错误,我无法弄清楚请帮助进行合并排序,,它显示出索引,但我无法弄清楚如何请任何人更新并请帮助我?
def mergesort(a,low,high):
if(low<high):
mid=(high+low)//2
mergesort(a,low,mid)
mergesort(a,mid+1,high)
merge(a,low,mid,high)
def merge(a,low,mid,high):
i=low
j=mid+1
while(i<=mid and j<=high):
if(a[i]<=a[j]):
print(a[i])
c.append(a[i])
i+=1
else:
c.append(a[j])
j+=1
a=[4,2,7,0,9,6,5]
c=[]
mergesort(a,0,len(a))
print(c)
我的合并排序算法不起作用
merge sort
it is showing error i cant able to figure out please help in merge sort,, It is showing out of index but i cant figure it out how please could anyone update and please help me?
def mergesort(a,low,high):
if(low<high):
mid=(high+low)//2
mergesort(a,low,mid)
mergesort(a,mid+1,high)
merge(a,low,mid,high)
def merge(a,low,mid,high):
i=low
j=mid+1
while(i<=mid and j<=high):
if(a[i]<=a[j]):
print(a[i])
c.append(a[i])
i+=1
else:
c.append(a[j])
j+=1
a=[4,2,7,0,9,6,5]
c=[]
mergesort(a,0,len(a))
print(c)
my merge sort algo not working
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
修复索引后,还会出现其他问题。 “合并排序”应该就地进行排序,修改原始列表。你没有那样做;您正在尝试建立一个新列表。这意味着您需要返回您创建的列表,并在下一个过程中使用它。
那么,
c
就不能是全局的。它是“合并”函数的本地函数,因此每个调用都有它自己的副本。最后,每个合并步骤仅处理列表的一部分。您必须复制未更改的部分。这似乎有效:After you fix the indexing, there are other problems. "Mergesort" is supposed to do a sort in place, modifying the original list. You're not doing that; you're trying to build up a new list. That means you need to RETURN the list you've created, and use that in the next pass.
Then,
c
cannot be a global. It's local to the "merge" function, so each call has it's own copy. Finally, each merge step only processed part of the list. You have to copy over the parts you aren't changing. This seems to work: