Quicksort函数在被调用时返回None

时间:2019-12-07 20:20:19

标签: python quicksort

我对quicksort的实际工作方式没有最好的了解,但是我一直在阅读有关堆栈溢出的其他文章并观看视频以了解它。但是,给了我一些入门代码一个基本的quicksort函数,并负责创建多个列表(已排序和未排序)以与quicksort一起使用。但是,我对这个quicksort函数实际返回的内容感到困惑。您无需亲自向我解释quicksort函数-我会自己解决,但我希望能帮助您了解如何实际调用它。

from random import *

def quicksort( myList, first, last ):
    """ Sort the given list using the quicksort algorithm. Sorts the
        portion of the list between the first and last indices (inclusive).
    """
    # base case: done when the indices touch or overlap.
    if first >= last: return

    # recursive case: partition the myList and recurse on both sides
    split = partition( myList, first, last )
    quicksort( myList, first, split-1 )
    quicksort( myList, split+1, last )

def partition( myList, first, last ):
    """ Partition the given list into two parts. Smaller and larger values of pivot btwn them
        Partitions the portion of the list between the first and last indices (inclusive).
        Return the index of the pivot element.
    """

    lastSmall = first

    # Separate the list into "pivot, smalls, lastSmall, larges".
    for i in range( first+1, last+1 ): # first+1 ... last (inclusive)
        # if myList[i] is small, swap it onto the 'small' side.
        if myList[ i ] <= myList[ first ]:
            lastSmall = lastSmall + 1
            swap( myList, lastSmall, i )

    # Swap the pivot with lastSmall to get "smalls, pivot, larges".
    swap( myList, first, lastSmall )

    # Return the location of the pivot
    return lastSmall

def swap( myList, first, second ):
    """ Swap the items at the first and second indices in the given list.
        Assumes the indices are legal and occupied in the list.
    """
    tmp = myList[ first ]
    myList[ first ] = myList[ second ]
    myList[ second ] = tmp

def main():

    ''' task 1 '''
    # randomized list
    pt1 = [randint(0,10) for x in range(10)]
    print(pt1) # print randomized list before quicksort
    pt1 = quicksort(pt1,0,len(task1pt1)-1)   # this keeps giving me None
    print(pt1) # print pt1 list after quicksort
    pt2 = [x for x in range(10)]
    print(pt2)


main()

如果我已经有了要排序的数字列表,那么我实际上应该怎么称呼quicksort?根据我在课堂上的记忆,我的教授告诉我们首先使用0,最后使用len(myList)-1,但我不明白quicksort会返回什么-它是列表吗?一个奇数?

1 个答案:

答案 0 :(得分:1)

quicksort函数不会返回已排序列表,但默认情况下会返回。但是,它按引用对列表进行排序。 pt1 = quicksort(...)行在对 pt1 进行排序后将其重新分配为“无”。因此,以下方法将起作用:

pt1 = [randint(0,10) for x in range(10)]
print(pt1) 
quicksort(pt1,0,len(pt1)-1)   
print(pt1) # prints the sorted list