我想知道当递归函数能够在没有回调的情况下到达其主体的尽头时会发生什么?



我最近一直在更新我对快速排序算法的知识。我知道列表(Python(是通过引用传递的,因此对其条目所做的任何更改都会反映在函数调用之外。该算法使用不带 return 语句的递归。我想知道函数到达其主体末端后会发生什么。return 语句(如果存在(会在"弹出"堆栈之前将值传递回直接调用者(如果我错了,请纠正我(。这种情况将继续发生,直到到达最后一个调用方。如果没有回电,那么上述过程是否会发生?

def quick_sort(arr,low,high):
# the Breaking statement
if (low < high):
# Partitoning
div = partition(arr,low,high)
quick_sort(arr,low,div) 
quick_sort(arr,div+1,high)
def partition(arr,low,high):
pivot = arr[low]
minIndex = low;
for i in range(low+1,high):
if arr[i] <= pivot:
minIndex += 1
arr[minIndex],arr[i] = arr[i],arr[minIndex]
arr[minIndex],arr[low] = pivot,arr[minIndex];
return  minIndex

当 python 函数到达其末尾时,它会返回 None。

https://www.askpython.com/python/python-return-statement

因此,quick_sort的最后一个调用返回 None,然后前一个调用在到达自己的末尾时返回 None,依此类推,直到第一个调用。

但是,由于不使用quick_sort的返回值(至少在您提供的代码中(,因此返回值无关紧要。

最新更新