from random import randint
def swap(array:[], index1, index2):
array[index1], array[index2] = array[index2], array[index1]
def partition(array:[], startIndex:int, endIndex:int) -> int:
pivot = array[endIndex]
lastLessorIndex = startIndex - 1
for i in range(startIndex, endIndex):
if array[i] <= pivot:
lastLessorIndex += 1
swap(array, i, lastLessorIndex)
lastLessorIndex += 1
swap(array, endIndex, lastLessorIndex)
return lastLessorIndex
def randomizedPartition(array:[], startIndex:int, endIndex:int) -> int:
swap(array, endIndex, randint(startIndex, endIndex))
return partition(array, startIndex, endIndex)
def randomizedSelect(array:[], startIndex:int, endIndex:int, targetOrder:int) -> int:
# targetOrder that begins with 0 serves more like an index.
if startIndex == endIndex:
return array[startIndex]
currentIndex = randomizedPartition(array, startIndex, endIndex)
targetIndex = startIndex + targetOrder
if currentIndex == targetIndex:
return array[currentIndex]
elif currentIndex < targetIndex:
return randomizedSelect(array, currentIndex+1, endIndex, \
targetIndex-currentIndex-1)
else:
return randomizedSelect(array, startIndex, currentIndex-1, targetOrder)
Randomized Select. Expected Θ(n).
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Effectively, factoring out the selectMedian function is q...
- 在SQL Server里面有top关键字可以很方便的取出前N条记录,但是Oracle里面却没有top的使用。解决方...
- Consider sorting n numbers stored in array A by first fin...