[英]Why do I have maximum recursion depth for Quick Sort in Python?
I am trying to implement the quick sort based on a pseudocode I was given, and I understand how the algorithm works.我正在尝试根据给出的伪代码实现快速排序,并且我了解该算法的工作原理。
When I run a test on the function and the input list is randomized, it runs perfectly fine.当我在 function 上运行测试并且输入列表是随机的时,它运行得非常好。
Yet, when I run a descending or ascending sorted list through the function I get the error of maximum recursion depth.然而,当我通过 function 运行降序或升序排序列表时,我得到最大递归深度的错误。 To my understanding, it is because the pivot I chose was not randomized, as in inputs of elements 900 and under, the code works fine, but once I put 1000 elements for a list that is not randomized I receive that error.
据我了解,这是因为我选择的 pivot 不是随机的,因为在元素 900 及以下的输入中,代码工作正常,但是一旦我将 1000 个元素放入未随机的列表中,我就会收到该错误。 I am unsure how to go about randomizing it without using the rand function.
我不确定 go 如何在不使用 rand function 的情况下随机化它。
I also tried using the mid point, but my output is incorrect and I cannot figure out why.我也尝试使用中点,但我的 output 不正确,我无法弄清楚为什么。
Any help and explanation would be appreciated.任何帮助和解释将不胜感激。
def quicksort(self, query_list, left, right):
if left < right:
mid = self.partition(query_list, left, right)
self.quicksort(query_list, left, mid - 1)
self.quicksort(query_list, mid + 1, right)
def partition(self, query_list, beg, end):
pivot = query_list[end]
i = beg - 1
for j in range(beg, end):
if query_list[j] >= pivot:
i = i + 1
(query_list[i], query_list[j]) = (query_list[j], query_list[i])
(query_list[i + 1], query_list[end]) = (query_list[end], query_list[i + 1])
return i + 1
Input a list rand: [3, 4, 8, 2, 0, 1]输入一个列表 rand:[3, 4, 8, 2, 0, 1]
Output: [8, 4, 3, 2, 1, 0] Output: [8, 4, 3, 2, 1, 0]
I tried:我试过了:
mid = (beg + end) // 2
pivot = query_list[mid]
My results:我的结果:
Input list at random: [8, 2, 4, 1, 9, 3, 7, 10, 6, 5]随机输入列表:[8, 2, 4, 1, 9, 3, 7, 10, 6, 5]
Output: [10, 9, 8, 6, 7, 1, 4, 3, 5, 2] Output: [10, 9, 8, 6, 7, 1, 4, 3, 5, 2]
To use middle element as pivot with the Lomuto partition scheme used in the question, swap middle element with last element:要使用问题中使用的 Lomuto 分区方案将中间元素用作 pivot,请将中间元素与最后一个元素交换:
def partition(self, query_list, beg, end):
mid = (beg+end)/2
query_list[mid],query_list[end] = query_list[end],query_list[mid]
pivot = query_list[end]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.