思路是利用快速排序:
因为快速排序的分治思想可以将查询的范围缩小
快速排序的思想:
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