我不确定 Quickselect 算法的时间复杂度(对于第 k 个最大元素),所以任何人都可以帮助我
def swap(arr,i,j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def partition(arr,left,right,p_index):
pivot = arr[p_index]
i = left-1
for j in range(left,right):
if arr[j] >= pivot:
i += 1
swap(arr,i,j)
swap(arr,i+1,p_index)
return i+1
def quickselect(arr,left,right,k):
if left == right:
return arr[left]
p_index = right
p_index = partition(arr,left,right,p_index)
if p_index == k:
return arr[p_index]
elif p_index > k:
return quickselect(arr,left,p_index-1,k)
else:
return quickselect(arr,p_index+1,right,k)