#在一个数组中,求第K小的数,时间复杂度O(n)
def bfprt(arr, begin, end, i):
if begin == end :
return arr[begin]
pivot = medianofMedians(arr,begin,end)
pivotRange = partition(arr, begin, end, pivot)
if(i >= pivotRange[0] and i <= pivotRange[1]):
return arr[i]
elif i< pivotRange[0]:
bfprt(arr, begin, pivotRange[0]-1, i)
else:
bfprt(arr, pivotRange[1]+1, end, i)
#中位数组成数组的中位数
def medianofMedians(arr, begin, end):
num = end - begin + 1
if num % 5== 0:
lenx=num//5
else:
lenx= num//5 + 1
newArr=[]
for i in range(lenx):
beginI = begin + i*5
endI = beginI + 4
newArr.append(getMedian(arr, beginI,min(end, endI)))
bfprt(newArr,0,lenx-1,lenx//2)
def getMedian(arr, begin, end):
insertsort(arr, begin, end)
sumx = begin + end
mid=sumx//2 + sumx%2
return arr[mid]
#插入排序
def insertsort(arr, begin, end):
cur = begin+1
while(cur <= end):
j = cur
while(j>0 and arr[j] < arr[j-1]):
arr[j],arr[j-1]=arr[j-1],arr[j]
j-=1
cur+=1
#相等区域的范围
def partition(arr, L, R, num):
less = L - 1
more = R + 1
while(L < more):
if arr[L] < num:
less += 1
swap(arr, L,less)
L += 1
elif arr[L] > num:
more -= 1
swap(arr, L, more)
else:
L+=1
return less+1,more-1
lst = [22,312,22,5,23,7,22]
ans = bfprt(lst,0,6,1)
print(ans)
BFPRT算法
最新推荐文章于 2024-02-09 08:39:07 发布