用堆排序找出list中第K小的数字, 用小顶堆
def min_heap_k(nums, topk):
def siftdown(nums, e, begin, end):
i = begin
j = 2*i + 1
while j < end:
if j+1 < end and num[j+1] < nums[j]:
j += 1
if e < nums[j]:
break
nums[i] = nums[j]
i = j
j = 2*i + 1
nums[i] = e
end = len(nums)
for k in range(end//2, -1, -1):
siftdown(nums, e, k, end)
for k in range(end-1, 0, -1):
e = nums[k]
topk -= 1
if topk == 0:
return nums[0]
siftdown(nums, e, 0, k)
if __name__ == "__main__":
print(min_heap_k([2, 3, 1, 5, -1, 0, -10, -9, -6], topk=4))
手写快速排序
def quicksort(nums):
quicksort_rec(nums, 0, len(nums)-1)
def quicksort_rec(nums, left, right):
if left >= right:
return None
i = left
j = right
k = nums[i]
while i<j:
while i<j and nums[j] > k:
j -= 1
if i < j :
nums[i] = nums[j]
i += 1
while i < j and nums[i] <k:
i += 1
if i < j :
nums[j] = nums[i]
j -= 1
nums[i] = k
quicksort_rec(nums, left, i-1)
quicksort_rec(nums, i+1, right)