我正在用Python实现一些排序算法,遇到了一个与超过最大递归深度有关的奇怪错误。在一个模块中,我实现了插入、合并和快速排序。然后在单独的模块中运行一些单元测试。对大值的快速排序给了我递归深度超出的错误。这是我在'分拣机.py':class QuickSort(Sorter):
"""Implements quicksort algorithm.
Best case: O(n*log(n))
Worst case: O(n^2)
Average case: O(n*log(n))
"""
@staticmethod
def partition(numbers, low, high):
pivot_index = low #crappy way to pick a pivot but it'll do
pivot_val = numbers[pivot_index]
#swap pivot with high
temp = numbers[high]
numbers[high] = pivot_val
numbers[pivot_index] = temp
store_index = low
for index in range(low, high):
if numbers[index] < pivot_val:
#Swap 'index' with 'store_index'
temp = numbers[store_index]
numbers[store_index] = numbers[index]
numbers[index] = temp
store_index += 1
#Swap pivot_val at high into appropriate index
temp = numbers[store_index]
numbers[store_index] = numbers[high]
numbers[high] = temp
return store_index
@staticmethod
def sort_helper(numbers, low, high):
if low < high:
part_index = QuickSort.partition(numbers, low, high)
QuickSort.sort_helper(numbers, low, part_index)
QuickSort.sort_helper(numbers, part_index+1, high)
return numbers
@classmethod
def sort(cls, numbers):
assert len(numbers) != 0, "Must provide a non-empty list"
return QuickSort.sort_helper(numbers, 0, len(numbers)-1)
我可以在本模块中运行以下测试:
^{pr2}$
在我的unittest模块中,我运行以下测试:def test_really_large(self):
"""Tests handling of a very large sequence."""
test_list = random.sample(xrange(1,10000), 5000)
real_sorted = sorted(test_list)
insert_sorted = InsertionSort.sort(test_list)
merge_sorted = MergeSort.sort(test_list)
quick_sorted = QuickSort.sort(test_list)
self.assertEqual(real_sorted, insert_sorted)
self.assertEqual(real_sorted, merge_sorted)
self.assertEqual(real_sorted, quick_sorted)
让我困惑的是,只有在运行unittest模块时才会抛出错误。当我尝试对5000个整数排序时,我得到一个错误。但是,当我在另一个模块中运行一个快速排序测试时,我可以对超过20000个整数进行排序,而不会引发错误。为什么会这样?在
感谢大家的快速反应。我认为每个人都正确地指出,我选择轴心点的劣质方法是导致已经排序的列表出现问题的原因。我会适当地修改这个。在