Quicksort不对下半部分进行排序

问题描述 投票:0回答:1

我不熟悉编程并尝试进行Udacity的快速排序实践。但是我的代码并没有完全做到这一点。

我在quicksort函数中分配低和高的方式可能有误,但我不知道如何解决它。

# this returns a sorted array
def quicksort(array):
    low = 0
    high = len(array) - 1
    if low >= high:
        return array
    pi = partition(array, low, high)
    array[:pi-1] = quicksort(array[:pi-1])
    array[pi+1:] = quicksort(array[pi+1:])
    return array

# this places the pivot in the right position in the array.
# all elements smaller than the pivot are moved to the left of it.    
def partition(array, low, high):
    border = low
    pivot = array[high]
    for i in range(low, high):
        if array[i] <= pivot:
            array[border], array[i] = array[i], array[border]
            border += 1
    array[border], array[high] = array[high], array[border]
    return border

test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)

预期答案:[1、3、4、6、9、14、20、21、21、25]

我得到的:[1、4、3、9、6、14、20、21、21、25]

python algorithm quicksort
1个回答
0
投票

要获得数组的下半部分,您需要执行array[:pi]而不是array[:pi-1]。结束索引是唯一的。如果将行更改为:

array[:pi] = quicksort(array[:pi])

您的算法有效:repl.it link

© www.soinside.com 2019 - 2024. All rights reserved.