我按照书中的算法来解决这个问题。当我打印结果时,它是不正确的。算法完全如书中所示 我的代码
import math
def quickSelect(A, k):
m = A[math.floor(len(A)/2)]
L = [i for i in A if i < m]
E = [i for i in A if i == m]
G = [i for i in A if i > m]
print(L)
print(E)
print(G)
if k <= len(L):
return quickSelect(L, k)
elif k <= (len(E) + len(G)):
return m
else:
return quickSelect(G, k- len(L) - len(E))
result = quickSelect([7, 14, 10, 12, 2, 11, 29, 3, 4], 4)
print(result)
答案 0 :(得分:3)
这些陈述:
L = [i for i in A if i < m] # less than m
E = [i for i in A if i == m] # equal to m
G = [i for i in A if i > m] # greater than m
将数组分为三个范围:
| L1 L2 L3 L4 | E1 | G1 G2 G3
| | |
0 | |
len(L) |
len(L) + len(E)
你的第二个范围的条件,
elif k <= (len(L) + len(G)):
return m
错了。它应该是:
elif k <= (len(L) + len(E)):
return m
节点:您可以使用Python的整数除法计算m
,而不是使用浮点数学:m = A[len(A) // 2]