Python实现查找数组中任意第k大的数字算法示例

时间:2022-11-19 21:05:53

本文实例讲述了Python实现查找数组中任意第k大的数字算法。分享给大家供大家参考,具体如下:

模仿partion方法,当high=low小于k的时候,在后半部分搜索,当high=low大于k的时候,在前半部分搜索。与快排不同的是,每次都减少了一半的排序。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def partitionOfK(numbers, start, end, k):
  if k < 0 or numbers == [] or start < 0 or end >= len(numbers) or k > end:
    return None
  low = start
  high = end
  key = numbers[start]
  while low < high:
    while low < high and numbers[high] >= key:
      high -= 1
    numbers[low] = numbers[high]
    while low < high and numbers[low] <= key:
      low += 1
    numbers[high] = numbers[low]
  numbers[low] = key
  if low < k:
    return partitionOfK(numbers, start + 1, end, k)
  elif low > k:
    return partitionOfK(numbers, start, end - 1, k)
  else:
    return numbers[low]
numbers = [3,5,6,7,2,-1,9,3]
print(sorted(numbers))
print(partitionOfK(numbers, 0, len(numbers) - 1, 5))

输出:返回了第五大排序的数字

[-1, 2, 3, 3, 5, 6, 7, 9]
6

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/weixin_36372879/article/details/84501054