快速排序---寻找无序数组中的第k大的数

思路是利用快速排序:

因为快速排序的分治思想可以将查询的范围缩小

快速排序的思想:

low为数组的起始点,high为数组的尾部点。交替扫描

1.固定数组的第一个数为定点,从数组的尾部high开始往左查找,直到第一个比定点小的数,和定点交换,因此当前点为空(high)

2.从数组的起始处,low找到第一个比定点大的数,赋值给High的位置

3.最后一层循环过后,low的位置是空缺的,补充定点的值。

递归分而治之

def quick_sort(tmp_list,start,end):
    if(start>=end):
        return
    low=start
    high=end
    tmp=tmp_list[start]
    print('high:%d,low:%d,index:%d'%(high,low,tmp))
    while(high>low):
        while high>low and tmp_list[high]>=tmp:
            high=high-1
        tmp_list[low]=tmp_list[high]
        while high>low and tmp_list[low]<=tmp:
            low=low+1
        tmp_list[high]=tmp_list[low]
    tmp_list[low]=tmp
    print('high:%d,low:%d'%(high,low))
    quick_sort(tmp_list,start,low-1)
    quick_sort(tmp_list,low+1,end)

第k大的值需要判断在当前定点的前面还是后面,如果是等于那就不费事了,不等于的话大于定点就要去后面找,小于需要去前面找

def findkth(tmp_list,start,end,k):
    if(start>=end):
        return
    low=start
    high=end
    tmp=tmp_list[start]
    while(high>low):
        while high>low and tmp_list[high]>=tmp:
            high=high-1
        tmp_list[low]=tmp_list[high]
        while high>low and tmp_list[low]<=tmp:
            low=low+1
        tmp_list[high]=tmp_list[low]
    tmp_list[low]=tmp
    if low==k:
        return tmp_list[low]
    elif low>k:
        return findkth(tmp_list,start,low-1,k)
    elif low<k:
        return findkth(tmp_list,low+1,end,k)
    else:
        return -999

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值