【问题标题】:Quicksort python implementation快速排序python实现
【发布时间】: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 代表b0 代表a

标签: python quicksort


【解决方案1】:

我认为您误解了 partition 中的 pivot 值的含义。它不是被分区的元素的索引。无论如何,直到函数结束。实际的主元值为lst[b],即被分区列表部分的最后一个元素。该值被移动到函数最后一行的下一行的pivot 位置。

pivot 值只是“高”值开始的索引。为pivot 选择一个随机初始值会破坏算法,因为它可能会从列表末尾递增(考虑如果random.randint(a, b) 返回b 会发生什么)。

如果您想要一个随机值进行分区,请选择一个随机索引并将其值与lst[b] 交换,然后正常运行算法的其余部分(pivot 索引从a 开始):

def partition(lst, a ,b):
    random_index = random.randint(a,b)  # pick random index, its value will be our pivot val
    lst[b], lst[random_index] = lst[random_index], lst[b]   # swap the value with lst[b]

    pivot = a        # run the rest of the partition code as it was in the original version
    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

【讨论】:

  • 啊,我想我明白你的意思了。我现在可以看到,在我的 for 循环中 pivot 正在递增,这就是导致它出现索引错误的原因。太棒了!
猜你喜欢
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多