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

yipeiwu_com6年前Python基础

本文实例讲述了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

PS:这里再为大家推荐一款关于排序的演示工具供大家参考:

在线动画演示插入/选择/冒泡/归并/希尔/快速排序算法过程工具:
http://tools.jb51.net/aideddesign/paixu_ys

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

用smtplib和email封装python发送邮件模块类分享

复制代码 代码如下:#!/usr/bin/python# encoding=utf-8# Filename: send_email.pyfrom email.mime.image imp...

简单了解Python3里的一些新特性

概述 到2020年,Python2的官方维护期就要结束了,越来越多的Python项目从Python2切换到了Python3。其实在实际工作中,很多伙伴都还是在用Python2的思维写Py...

python删除指定类型(或非指定)的文件实例详解

本文实例分析了python删除指定类型(或非指定)的文件用法。分享给大家供大家参考。具体如下: 如下,删除目录下非源码文件 import os import string de...

python3 面向对象__类的内置属性与方法的实例代码

0.object类源码 class object: """ The most base type """ def __delattr__(self, *args, **kwa...

python基于pyDes库实现des加密的方法

本文实例讲述了python基于pyDes库实现des加密的方法。分享给大家供大家参考,具体如下: 下载及简介地址:https://twhiteman.netfirms.com/des.h...