【发布时间】:2019-12-08 04:49:26
【问题描述】:
我对快速排序的实际工作原理没有最好的了解,但我一直在阅读有关堆栈溢出的其他帖子并观看视频以了解它。然而,我得到了一些入门代码,一个基本的快速排序功能,并负责创建几个排序和未排序的列表,以便与快速排序一起使用。但是,我对这个快速排序函数实际返回的内容感到困惑。您不必亲自向我解释快速排序功能 - 我会自己解决,但我很乐意帮助您了解如何实际调用它。
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()
如果我已经有一个想要排序的数字列表,我实际上应该如何调用快速排序?根据我在课堂上的记忆,我的教授告诉我们首先使用 0,最后使用 len(myList)-1,但我不明白快速排序返回什么 - 它是一个列表吗?单数?
【问题讨论】:
-
Quicksort 接受一个列表并对该列表进行排序:在您发布的代码的情况下,该列表直接发生了变异。换句话说,它应该返回 None。