我不得不用自己选择的语言实现作业的快速排序算法,我选择了Python。
在讲座中,我们被告知QuickSort是内存高效的,因为它在适当的位置工作;也就是说,它没有用于递归的输入数组部分的额外副本。
考虑到这一点,我试图在Python中实现QuickSort算法,但不久之后意识到,为了编写一段优雅的代码,我必须在递归时将数组的一部分传递给函数本身。由于Python每次都会创建新的列表,所以我尝试使用Python3(因为它支持非本地关键字)。下面是我的注释代码。
def quicksort2(array):
# Create a local copy of array.
arr = array
def sort(start, end):
# Base case condition
if not start < end:
return
# Make it known to the inner function that we will work on arr
# from the outer definition
nonlocal arr
i = start + 1
j = start + 1
# Choosing the pivot as the first element of the working part
# part of arr
pivot = arr[start]
# Start partitioning
while j <= end:
if arr[j] < pivot:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i += 1
j += 1
temp = arr[start]
arr[start] = arr[i - 1]
arr[i - 1] = temp
# End partitioning
# Finally recurse on both partitions
sort(start + 0, i - 2)
sort(i, end)
sort(0, len(array) - 1)
现在,我不确定我是做得好还是漏掉了什么。我已经编写了一个更像Pythonic的QuickSort版本,但这肯定不起作用,因为它总是返回部分输入数组并将它们连接起来。
我的问题是,这是用Python实现的方法吗?我搜索过Google和SO,但还没有找到一个真正的QuickSort的就地实现,所以我想最好问问。
下面是另一个实现:
当然不是最好的方法,加上这个著名的算法将有几十个完美的实现。。这是我的,很容易理解
好的,首先是分区子程序的一个独立函数。它需要阵列, 兴趣的起点和终点,以及轴的索引。这些功能应该是清楚的
快速排序然后在整个数组上第一次调用分区子例程;然后 调用recursevely本身,将所有内容按轴进行排序,然后再进行排序。
问你是否不明白
我最近开始学习python,下面是我使用python实现quicksort的尝试。希望能有所帮助。欢迎反馈:)
相关问题 更多 >
编程相关推荐