0
我想在Python 3的整數ctypes數組上實現幾個排序方法,並且似乎無法找出Quicksort方法。我相信我的大部分代碼是正確的,但我只是錯過了一個愚蠢的聲明。現在,當我嘗試打印返回的數組時,我得到的是一個'NoneType'對象。Quicksorting cType數組數組
非常感謝。
#Quicksort Algorithm
def quicksort(list):
n = len(list)
return recquick(list, 0, n-1)
#Recursive Quicksort Function
def recquick(list, first, last):
#Base Case
if first >= last:
return
else:
#Save pivot value
pivot = list[first]
pos = partseq(list, first, last)
#Repeat the process on the two subsequences
recquick(list, first, pos-1)
recquick(list, pos+1, last)
#Partitions subsequence using first key as pivot
def partseq(list, first, last):
#Save pivot value
pivot = list[first]
#Find pivot position and move elements around the pivot
left = first + 1
right = last
while left <= right:
#Find the first key larger than the pivot
while left < right and list[left] < pivot:
left += 1
#find the last key in the sequence that is smaller than the pivot
while right >= left and list[right] >= pivot:
right -= 1
#Swap the two keys
if left < right:
tmp = list[left]
list[left] = list[right]
list[right] = tmp
#Put the pivot in the proper position
if right != first:
list[first] = list[right]
list[right] = pivot
#Return index position of the pivot value
return right
是指出'quicksort'沒有return語句(從而返回'None')多餘的結果呢? :P – akaIDIOT 2013-03-28 08:18:09
是的,對不起,即使我將它改爲'return recquick(list,0,n-1)',問題仍然存在。 – 2013-03-28 08:20:12
那麼,在那個時候,'recquick'永遠不會返回列表。你的代碼似乎是在'就地'排序列表,如果你檢查你插入的列表,是否恰巧被排序(或者至少與你開始運行時不同)? – akaIDIOT 2013-03-28 08:27:09