python实现快速选择算法
参考资料
代码实现
import random
# 根据快排算法改进的快速选择算法
def quickselect(mylist, k):
randomIndex = random.randint(0, len(mylist) - 1)
print(f"randomIndex:{randomIndex}")
pivot = mylist[randomIndex]
print(f"pivot:{pivot}")
left = []
right = []
mid = []
for i in mylist:
if i < pivot:
left.append(i)
elif i > pivot:
right.append(i)
elif i == pivot:
mid.append(i)
if len(right) >= k:
pivot = quickselect(right, k)
elif len(right) + len(mid) < k:
pivot = quickselect(left, k - len(right) - len(mid))
return pivot
input_list = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(f"input_list:{input_list}")
number_k_value = quickselect(mylist=input_list, k=1)
print(f"number_k_value:{number_k_value}")
本文来自博客园,作者:JaxonYe,转载请注明原文链接:https://www.cnblogs.com/yechangxin/articles/16909470.html
侵权必究