0
我已經實現了這個快速排序,但我似乎有錯誤,我不能修復,有人會介意快速看看它嗎?Python快速排序調試
我給出的例子的輸出接近答案,但一些指數錯位。
def partition(array, pivot, start, end):
# move pivot to the end
temp = array[pivot]
array[pivot] = array[end]
array[end] = temp
i = start
j = end - 1
while(i < j):
# check from left for element bigger than pivot
while(i < j and array[end] > array[i]):
i = i + 1
# check from right for element smaller than pivot
while(i < j and array[end] < array[j]):
j = j - 1
# if we find a pair of misplaced elements swap them
if(i < j):
temp = array[i]
array[i] = array[j]
array[j] = temp
# move pivot element to its position
temp = array[i]
array[i] = array[end]
array[end] = temp
# return pivot position
return i
def quicksort_helper(array, start, end):
if(start < end):
pivot = (start + end)/2
r = partition(array, pivot, start, end)
quicksort_helper(array, start, r - 1)
quicksort_helper(array, r + 1, end)
def quicksort(array):
quicksort_helper(array, 0, len(array) - 1)
array = [6, 0, 5, 1, 3, 4, -1, 10, 2, 7, 8, 9]
quicksort(array)
print array
我有一種感覺,答案是顯而易見的,但我不能找到它。
希望的輸出:
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
實際輸出:
[-1, 0, 2, 3, 1, 4, 5, 6, 7, 8, 9, 10]
是,去獲得一個橡皮鴨子,它會做的工作。 https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – jmoon
所以我可能應該提到我有一個類似的解決方案,在我改變我