我得到了以下 quickSelect 算法的伪代码。我对一些事情有点困惑,当我调用 quickSelect 方法时,我要为“k”发送什么。另外,因为我需要在方法的开头声明 count = 0,所以它总是会在 quickSelect 的递归调用中设置回 0 这不是我需要发生的谢谢你的帮助,我已经包含了 Pseudo -code 以及我下面的代码;
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)