2016-07-31 137 views
1

我想在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) 
+1

完整回溯添加到您的問題。它會告訴你你的代碼在哪裏失敗 –

+0

你知道嗎?如果沒有,請參閱 –

回答

1
elif a[pivot] > a[right] : 
     temp = a[right] 
     a[right] = a[pivot] 
     a[pivot] = a[temp] 
     pivot = right 

通知。您需要將其設置爲temp

這裏:

elif a[pivot] < a[left] : 
     temp = a[left] 
     a[left] = a[pivot] 
     # a[pivot] = a[temp] 
     a[pivot] = temp 
     pivot = left 

更妙的是,使用元組拆包 - 你不需要溫度:

elif a[pivot] > a[right] : 
     a[pivot], a[right] = a[right], a[pivot] 
     """ 
     temp = a[right] 
     a[right] = a[pivot] 
     a[pivot] = a[temp] 
     """ 
+0

以下的答案,這樣我就能從列表中找出錯誤。感謝joel .it現在的工作 –

+0

我知道它的工作。我測試了它。你可以檢查我的答案,如果它解決了你的問題@KritiSahu –