简体   繁体   English

python初始条件下的quicksort算法

[英]quicksort algorithm in python initial condition

In the following implementation of the quicksort algorithm in Python: 在Python中快速排序算法的以下实现中:

def quicksort(listT):
    greater=[]
    lower=[]
    pivot=[]
    if len(listT)<=1:
        return listT
    else:
        pivot=listT[0]
        for i in listT:
            if i<pivot:
                lower.append(i)
            elif i>pivot:
                greater.append(i)
            else:
                pivot.append(i)
        lower=quicksort(lower)
        greater=quicksort(greater)
        return lower+pivot+greater

I was wondering what exactly the first condition does in this implementation, for what I see when it divides each part of the list into a greater and lower part, according to the pivot, there would be a moment in which the list has a length lower than 1, but this returned list is not concatenated in any way. 我想知道在此实现中第一个条件究竟是做什么的,因为根据透视图,当将列表的每个部分分为较大和较低部分时,我会看到列表的长度较短大于1,但是此返回列表未以任何方式连接在一起。 Could this condition be changed? 这个条件可以改变吗?

The len(listT)<=1 is needed to terminate the recursion. 需要len(listT)<=1终止递归。 Quicksort works by dividing the problem into more easily solved subproblems. Quicksort通过将问题分为更容易解决的子问题来工作。 When the subproblem is an empty list or list of length one, it is already solved (no sorting needed) so the result can be returned directly. 当子问题为空列表或长度为1的列表时,该子问题已解决(无需排序),因此可以直接返回结果。

If the initial condition is not stated, then the sort will fail at either 如果未声明初始条件,则排序将在任一条件下失败

  • pivot=listT[0] # because the list may be empty and it will reference an invalid index, or ivot = listT [0]#,因为列表可能为空,并且将引用无效的索引,或者

  • lower=quicksort(lower) # actually it will never end because the stack keeps building on this line. lower = quicksort(lower)#实际上,它永远不会结束,因为堆栈一直在此行上构建。

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

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