我想在Python中編寫快速排序,但無法糾正錯誤?我如何解決所有這些錯誤?邏輯有什麼問題嗎?Python中的快速排序代碼
Traceback (most recent call last):
line 35, in module
line 5, in quicksort
line 3, in quicksort
line 30, in partition
IndexError: list index out of range
這裏是我的代碼:您設置a[pivot]
到a[temp]
def quicksort(a, beg, end):
if beg < end:
split = partition(a, beg, end)
quicksort(a, beg, split-1)
quicksort(a, split+1, end)
def partition(a, beg, end):
left = beg
right = end
pivot = left
done = True
while done:
while a[pivot] <= a[right] and pivot != right:
right = right - 1
if pivot == right:
done = False
elif a[pivot] > a[right] :
temp = a[right]
a[right] = a[pivot]
a[pivot] = a[temp]
pivot = right
while a[pivot] >= a[left] and pivot != left:
left = left + 1
if pivot == left:
done = False
elif a[pivot] < a[left] :
temp = a[left]
a[left] = a[pivot]
a[pivot] = a[temp]
pivot = left
return pivot
a = [4, 5, 7, 3, 6, 22, 45, 82]
quicksort(a, 0, len(a)-1)
print(a)
完整回溯添加到您的問題。它會告訴你你的代碼在哪裏失敗 –
你知道嗎?如果沒有,請參閱 –