Python中的quickSelect硬件
我得到了以下quickSelect算法的伪代码。当我调用quickSelect方法时,我对一些事情感到有点困惑,我为“k”发送了什么。另外,因为我需要在方法开始时声明count=0,所以在quickSelect的递归调用中,它总是会被设置回0,这不是我需要的。感谢您的帮助,我已经包括了伪代码以及下面的代码Python中的quickSelect硬件,python,Python,我得到了以下quickSelect算法的伪代码。当我调用quickSelect方法时,我对一些事情感到有点困惑,我为“k”发送了什么。另外,因为我需要在方法开始时声明count=0,所以在quickSelect的递归调用中,它总是会被设置回0,这不是我需要的。感谢您的帮助,我已经包括了伪代码以及下面的代码 Function quickSelect(aList, k): If aList is not empty: pivot <- Choose the element at pos
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)
函数quickSelect(列表,k):
如果列表不为空:
pivot首先,您需要smallerList
和largerList
根据pivot两侧的索引(而不是值)获取内容。Pivot应该将数字除以索引的内容,而不是索引的位置(例如,如果索引为5,则所有小于数字5的条目都需要分配给smallerList
,所有较大的数字都需要分配给大于5的largerList
)
这可以通过一个简单的for循环完成:
if len(aList)!=0:
pivot=aList[(len(aList)//2)]
smallerList = []
for i in aList:
if i<pivot:
smallerList.append(i)
largerList=[]
for i in aList:
if i>pivot:
largerList.append(i)
m=len(smallerList)
count=len(aList)-len(smallerList)-len(largerList)
或者,如果较小列表的长度大于k,则仅使用smallerList
,而不使用完整列表,再次运行快速选择
elif m > k:
return quickSelect(smallerList,k)
否则,使用较大的列表(而不是完整的列表)再次运行快速选择,并查找pivot的较小列表计数的k长度
else:
return quickSelect(largerList, k - m - count)
此函数将反复运行(比线性排序快得多),并在满足条件后返回pivot。在这种情况下,pivot将是中间值
希望这会有所帮助!首先,您有smallerList
和largerList
根据索引(而不是索引值)从数据轴两侧获取内容。数据轴应该将数字除以索引的内容,而不是索引的位置(假设索引为5,则所有小于数字5的条目都需要分配给smallerList
,而所有大于数字的条目都需要分配给大于5的largerList
)
这可以通过一个简单的for循环完成:
if len(aList)!=0:
pivot=aList[(len(aList)//2)]
smallerList = []
for i in aList:
if i<pivot:
smallerList.append(i)
largerList=[]
for i in aList:
if i>pivot:
largerList.append(i)
m=len(smallerList)
count=len(aList)-len(smallerList)-len(largerList)
或者,如果较小列表的长度大于k,则仅使用smallerList
,而不使用完整列表,再次运行快速选择
elif m > k:
return quickSelect(smallerList,k)
否则,使用较大的列表(而不是完整的列表)再次运行快速选择,并查找pivot的较小列表计数的k长度
else:
return quickSelect(largerList, k - m - count)
此函数将反复运行(比线性排序快得多),并在满足条件后返回pivot。在这种情况下,pivot将是中间值
希望这能有所帮助!您的代码在哪些方面不起作用?(您能在所需输出的同时提供一些输出示例吗?)您的代码在哪些方面不起作用?(您能在所需输出的同时提供一些输出示例吗?)