Python mergesort递归版本Intution
我在一本书中找到了mergesort程序的以下部分:Python mergesort递归版本Intution,python,sorting,mergesort,Python,Sorting,Mergesort,我在一本书中找到了mergesort程序的以下部分: def sort(v): if len(v)<=1: return v mid=len(v)//2 v1,v2=sort(v[:mid]),sort(v[mid:]) return merge(v1,v2) 在最后一部分中,我不知道是否应该调用merge和v[5]以及v=[2,4]来进行排序,是这样的吗?还是我遗漏了什么 有任何帮助或如何正确解释此源代码吗 感谢为了演示mergesort是
def sort(v):
if len(v)<=1:
return v
mid=len(v)//2
v1,v2=sort(v[:mid]),sort(v[mid:])
return merge(v1,v2)
在最后一部分中,我不知道是否应该调用merge和v[5]以及v=[2,4]来进行排序,是这样的吗?还是我遗漏了什么
有任何帮助或如何正确解释此源代码吗
感谢为了演示mergesort是如何工作的,我介绍了我自己的实现,这是我不久前写的:
def mergesort(lst):
# SORT PART ------------------------------------------------
# base case: return just this list if length = 1
if len(lst) <= 1:
return lst
# recursive case: do mergesort() on either half of the list
mid = len(lst) // 2
sub1, sub2 = mergesort(lst[:mid]), mergesort(lst[mid:])
# MERGE PART ------------------------------------------------
# merge sub1 and sub2, which are each sorted
sorted_lst = []
while sub1 and sub2: # ...are not empty...
# remove the lesser element from the front of sub1 or sub2 and add it to sorted list
sorted_lst.append(sub1.pop(0) if sub1[0] < sub2[0] else sub2.pop(0))
# finally, once one of the lists are empty, append the remainder of the other list.
sorted_lst += (sub1 if sub1 else sub2)
# and return the now-sorted list
return sorted_lst
def合并排序(lst):
#分类部分------------------------------------------------
#基本情况:如果长度=1,则仅返回此列表
如果在自顶向下的合并排序中len(lst),则在两种基本情况下合并才会开始,其中子数组大小已减少到单个元素。在这之后,合并和拆分继续在调用链上下移动,深度优先,通常先离开
对于问题示例代码,递归将重复沿着排序的左路径(v[:mid]),直到在该实例返回以允许第二次调用排序(v[mid:])之前到达一个基本情况下的一个元素,这可能是两个元素,在这种情况下,再发生一级递归,然后开始合并。,但我想知道我发现的实现是如何实现的works@Little您会注意到,除了变量名之外,我的实现几乎是相同的。还包括合并部分。例如,在您的版本中,您的代码何时达到whilesub1和sub2?是否因为列表被分为多个块而在列表用尽后到达?或者每次递归调用中都会到达while部分?@除了最后一个递归调用(与基本情况相符)之外,每次递归调用最终都会到达while部分,但顺序相反[1]
和[2]
将合并在一起,[3]
和[4]
将合并在一起,然后父调用将[1,2]
和[3,4]
合并到它启动的任何其他递归调用中,等等当您递归时,您不会退出该函数,而是在使用不同的参数执行该函数之后返回该函数。
def mergesort(lst):
# SORT PART ------------------------------------------------
# base case: return just this list if length = 1
if len(lst) <= 1:
return lst
# recursive case: do mergesort() on either half of the list
mid = len(lst) // 2
sub1, sub2 = mergesort(lst[:mid]), mergesort(lst[mid:])
# MERGE PART ------------------------------------------------
# merge sub1 and sub2, which are each sorted
sorted_lst = []
while sub1 and sub2: # ...are not empty...
# remove the lesser element from the front of sub1 or sub2 and add it to sorted list
sorted_lst.append(sub1.pop(0) if sub1[0] < sub2[0] else sub2.pop(0))
# finally, once one of the lists are empty, append the remainder of the other list.
sorted_lst += (sub1 if sub1 else sub2)
# and return the now-sorted list
return sorted_lst