Posted in Python onJanuary 23, 2019
本文实例讲述了Python实现查找数组中任意第k大的数字算法。分享给大家供大家参考,具体如下:
模仿partion方法,当high=low小于k的时候,在后半部分搜索,当high=low大于k的时候,在前半部分搜索。与快排不同的是,每次都减少了一半的排序。
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实现查找数组中任意第k大的数字算法示例
- Author -
hustfc声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@