def insert_sort(l: list):
for i in range(len(l)):
for j in range(i, 0, -1):
if l[j] < l[j - 1]:
l[j], l[j - 1] = l[j - 1], l[j]
return l
def quick_sort(l: list):
length = len(l)
if length <= 30:
return insert_sort(l) # 数据量低于某个指标时采用插入排序,吸取算法的常数时间优越性
p_index = random.randint(0, length - 1) # 考虑均衡数据样本数据的复杂度
p = l[p_index]
less = -1 # 小于n的区域
more = length # 大于n的区域
index = 0 # 当前索引位置
while index < more:
if l[index] < p:
less += 1 # 小于n区域右移1
l[index], l[less] = l[less], l[index]
index += 1 # 当前位置加1
elif l[index] > p:
more -= 1 # 大于n区域左移1,当前位置不变
l[index], l[more] = l[more], l[index]
else:
index += 1 # 当前位置加1
return quick_sort(l[0:less + 1]) + l[less + 1:more] + quick_sort(l[more:])
网友评论