我已經給出了quickSelect算法的以下僞代碼。當我將quickSelect方法稱爲'k'時,我對一些事情有點困惑。另外,因爲我需要在方法的開頭聲明count = 0,所以在quickSelect的遞歸調用中它總是會回到0,這不是我需要發生的事情感謝您的幫助,我已將Pseudo代碼以及我的代碼如下;quickSelect在Python中的HW
Function quickSelect(aList, k):
If aList is not empty:
pivot <- Choose the element at position (len(alist)//2)
smallerList <- All elements of aList smaller than pivot
largerList <- All elements of aList larger than pivot
count <- the number of occurences of pivot value in aList
m <- the size of smallerList
if k >= m and k < m + count then:
return pivot
if m > k:
return quickSelect(smallerList,k)
else:
return quickSelect(largerlist, k-m-count)
這是我想出來的:
def quickSelect(aList, k):
pivot = aList[len(aList)//2]
smallerList = aList[:pivot]
largerList = aList[pivot:]
m = len(smallerList)
count = 0
for i in aList:
if i == pivot:
count = count + 1
if k >= m and k < m + count:
return pivot
if m > k:
return quickSelect(smallerList, k)
else:
return quickSelect(largerList, k-m-count)
你的代碼不工作的方式是什麼? (你能否提供一些與期望輸出一起的輸出示例?) –