python3 快速排序列表索引超出范围

python3 quicksort list index out of range

嗨,我是 Python 的新手,当我为快速排序算法实现以下代码时,我得到了回溯:"IndexError: list index out of range".

谁能帮帮我,拜托。挣扎了一晚上!

谢谢!

def quicksort(array,l,r):
    n = len(array)
    if n == 1 or n == 0:
        return array
    else:
        p = array[l]
        i = l + 1
        for j in range(l+1, r):
            if array[j] < p:
                array[i], array[j] = array[j], array[i]
                i = i + 1
        array[l], array[i-1] = array[i-1], array[l]
        array[l:i-1] = quicksort(array[l:i-1],l,i-1)
        array[i:r] = quicksort(array[i:r],i,r)
        return array

testarray = [1,3,4,5,2]
sortedarray = quicksort(testarray,0,5) 

修复了错误,但我认为你的排序逻辑是错误的

def quicksort(array,l,r):
    n = len(array)
    if n == 1 or n == 0:
        return array
    else:
        p = array[l]
        i = l + 1
        for j in range(1, r-1):  # r is length of array; so range should be one less
            if array[j] < p:
                array[i], array[j] = array[j], array[i]
                i = i + 1
        array[l], array[i-1] = array[i-1], array[l]
        array[l:i-1] = quicksort(array[l:i-1],l,i-1)
        array[i:r] = quicksort(array[i:r],i,r)
        return array

testarray = [1,3,4,5,2]
sortedarray = quicksort(testarray,0,5) 

print(sortedarray)

输出

[1, 3, 2, 4, 5]