简体   繁体   English

Python Quicksort递归深度

[英]Python quicksort recursive depth

I am trying to find how far the recursive function descends ie the deepest level of recursion, in the following quick sort code, i have been told to edit the qsort function and would appreciate any help 我试图找出递归函数的下降幅度,即递归的最深层次,在下面的快速排序代码中,有人告诉我编辑qsort函数,希望对您有所帮助

def partition(lst, lo, hi):
    part = lo
    while lo < hi:
           while lst[lo] <= lst[part] and lo < hi:
                lo += 1
           while lst[hi] > lst[part]: # Don't have to check for hi >= 0 cos part is there as a sentinel.
                hi -= 1
           if lo < hi:
               # Swap the two entries
               lst[hi], lst[lo] = lst[lo], lst[hi]
       # Swap part into position
    if lst[part] > lst[hi]: # (this may happen of the array is small (size 2))
            lst[part], lst[hi] = lst[hi], lst[part]
    print(part)
    return hi
def rec_qsort(lst, lo, hi):
    if lo < hi:
       pivot = partition(lst, lo, hi)
       rec_qsort(lst, lo, pivot - 1)
       rec_qsort(lst, pivot + 1, hi)
def qsort(lst):
    rec_qsort(lst, 0, len(lst) - 1)
    return lst

Pass depth as an optional parameter, default 0, to your implementation function rec_qsort. 将depth作为可选参数(默认为0)传递给实现函数rec_qsort。 Add one when you recurse deeper. 递归越深时,再添加一个。

def function(data, depth=0):
    if len(data) > 1:
        mid = len(data)/2
        function(data[:mid], depth+1)
        function(data[mid:], depth+1)
    print "depth", depth, "length", len(data), data

data = range(10)
function(data)

Obviously print at the beginning if you want to see the order of calls, print at the end if you want them in order by when they return. 如果要查看呼叫的顺序,显然要在开始时打印,如果要让它们在返回时按顺序进行,则要在末尾打印。 Add a watch instead of printing if you just want to see depth while debugging. 如果您只想在调试时看到深度,则添加手表而不是打印。

from user pjs: The maximum depth of quicksort, measured directly, can be anything between log(n) and n. 来自用户pjs的信息:快速排序的最大深度(直接测量)可以在log(n)和n之间。 The expected depth for randomized data or a randomly selected pivot is proportional to log(n) 随机数据或随机选择的枢轴的预期深度与log(n)成正比

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM