我是 Python 新手,我正在练习编写代码,但我遇到了一些麻烦。
我正在尝试实现QuickSelect以提取K 最大元素。
这是我的代码;
def partition(A, left, right):
pivot = random.randrange(left, right) # pick a random number as pivot
i = left - 1
for j in range(left, right):
if A[j] <= pivot:
i = i+1
A[i], A[j] = A[j], A[i]
A[i+1], A[right] = A[right], A[i+1]
return i+1
def QuickSelect(A, K, left, right): # Array, K-th element
if left == right:
return A[left]
q = partition(A, left, right)
i = q - left + 1
if K == i:
return A[i]
if K < i:
return QuickSelect(A, K, left, q - 1)
else:
return QuickSelect(A, K - i, q + 1, right)
尝试实现算法以获得第 5 个最高元素:
a = get_random_array(10, 100)
print("array unsorted=" , a)
print("array sorted=", sorted(a))
print("result:" , QuickSelect(A = a, K = 5, left = 0, right = len(a)-1)) #I want the 5-th highest element
得到这个结果:
array unsorted = [71, 34, 0, 36, 26, 15, 3, 69, 93, 85]
array sorted = [0, 3, 15, 26, 34, 36, 69, 71, 85, 93]
result: 3
结果是错误的,因为 3 不是第 5 个最高元素。
错误是在partition(A, left, right)
还是在QuickSelect(A, K, left, right)
?你能帮我解决它吗?谢谢!