algorithm-in-python/sort/select.py

58 lines
1.4 KiB
Python
Raw Permalink Normal View History

2018-07-08 23:28:29 +08:00
''' mbinary
#########################################################################
# File : select.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# Blog: https://mbinary.xyz
2018-07-08 23:28:29 +08:00
# Github: https://github.com/mbinary
# Created Time: 2018-07-06 17:13
# Description:
#########################################################################
'''
2018-07-08 16:41:55 +08:00
from random import randint
2020-04-15 12:28:20 +08:00
def select(lst, i):
2018-07-08 16:41:55 +08:00
lst = lst.copy()
2020-04-15 12:28:20 +08:00
def partition(a, b):
2018-07-08 16:41:55 +08:00
pivot = lst[a]
2020-04-15 12:28:20 +08:00
while a < b:
while a < b and lst[b] > pivot:
b -= 1
if a < b:
2018-07-08 16:41:55 +08:00
lst[a] = lst[b]
2020-04-15 12:28:20 +08:00
a += 1
while a < b and lst[a] < pivot:
a += 1
if a < b:
2018-07-08 16:41:55 +08:00
lst[b] = lst[a]
2020-04-15 12:28:20 +08:00
b -= 1
lst[a] = pivot
2018-07-08 16:41:55 +08:00
return a
2020-04-15 12:28:20 +08:00
def _select(a, b):
if a >= b:
return lst[a]
2018-07-08 16:41:55 +08:00
# randomized select
2020-04-15 12:28:20 +08:00
n = randint(a, b)
lst[a], lst[n] = lst[n], lst[a]
pos = partition(a, b)
if pos > i:
return _select(a, pos-1)
elif pos < i:
return _select(pos+1, b)
else:
return lst[pos]
return _select(0, len(lst)-1)
2018-07-08 16:41:55 +08:00
2020-04-15 12:28:20 +08:00
if __name__ == '__main__':
lst = [randint(0, 1000) for i in range(100)]
2018-07-08 16:41:55 +08:00
st = sorted(lst)
for i in range(10):
2020-04-15 12:28:20 +08:00
n = randint(0, 99)
print('select {}th: \nexpect: {}\ngot: {}'.format(
n, st[n], select(lst, n)))