【发布时间】:2016-03-09 10:38:35
【问题描述】:
我正在尝试编写一个快速排序的实现,其中枢轴元素是伪随机的。我在网上查看了各种帖子,其中很多是关于 SO 的,但我仍然遇到问题。这是我的代码:
def quickSort(lst, a, b):
if a < b:
pivot = partition(lst, a, b)
quickSort(lst, a, pivot-1)
quickSort(lst, pivot+1, b)
return lst
def partition(lst, a ,b):
pivot = random.randint(a,b)
for i in range(a,b):
if lst[i] < lst[b]:
lst[i],lst[pivot] = lst[pivot],lst[i]
pivot += 1
lst[pivot],lst[b] = lst[b],lst[pivot]
return pivot
此代码实际上与为回答此问题提供的代码相同:quick sort python recursion,但我没有使用 start 元素作为枢轴,而是使用随机。我不断收到此错误:
in partition
lst[pivot],lst[b] = lst[b],lst[pivot]
IndexError: list index out of range
我已经查过了,我认为这意味着我正在尝试引用列表中不存在或超出列表范围的元素。为什么会这样?
我也尝试使用此链接中实现的快速排序样式,但我得到了同样的错误:Quicksort implementation in Python
【问题讨论】:
-
random.randint从[a, b]生成一个随机数。您可能需要从b中减去 1,然后再将其传递给randint。 -
@vaultah 刚试过。得到完全相同的错误
-
好吧,如果你只是
print(len(lst), b, pivot),你应该可以看到问题是什么 -
你最初是怎么打电话给
quicksort的?具体来说,您传递的b是什么?如果你使用len(lst),你会得到IndexErrors,就像现在一样。 -
@Blckknght 我使用
len(lst)-1代表b和0代表a