Quicksort python实现

时间:2016-03-08 20:44:04

标签: python quicksort

我正在尝试编写quicksort的实现,其中pivot元素是伪随机的。我在网上查看过各种帖子,很多都是关于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样式,我收到同样的错误:Quicksort implementation in Python

1 个答案:

答案 0 :(得分:0)

我认为您误解了pivotpartition值的含义。它不是被分割的元素的索引。直到功能结束才开始。实际的透视值是lst[b],是要分区的列表部分中的最后一个元素。该值将移动到函数最后一行的下一个pivot位置。

pivot值只是&#34; high&#34;的索引。价值观开始。选择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