Files
sanguo_moziplus_v2/src/algorithms/find_max_quickselect.py
T
cfdaily ac8444bb41
CI / lint (pull_request) Successful in 19s
CI / test (pull_request) Failing after 42s
CI / frontend (pull_request) Successful in 19s
CI / notify-on-failure (pull_request) Successful in 1s
[moz] feat(algorithms): 三种排序算法实现最大值查找
- find_max_linear: 线性扫描 O(n)(原 find_max 重命名+alias兼容)
- find_max_bubble: 冒泡排序 O(n²)
- find_max_quickselect: 快速选择 partition O(n) avg
- 37 个测试(7×3 参数化 + 9 一致性 + 7 原有)
2026-06-22 06:25:22 +08:00

42 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""find_max_quickselect — 快速选择 partition 思路找最大值"""
from __future__ import annotations
import random
def find_max_quickselect(nums: list[int | float]) -> int | float | None:
"""使用快速选择的 partition 思路直接找最大值,空列表返回 None。"""
if not nums:
return None
arr = list(nums) # 不修改原列表
return _quickselect_max(arr, 0, len(arr) - 1)
def _quickselect_max(arr: list[int | float], lo: int, hi: int) -> int | float:
"""在 arr[lo..hi] 中找最大值。
Lomuto partition: < pivot 左,>= pivot 右。
pivot 落在 store 位置,最大值在 [store, hi]。
"""
if lo == hi:
return arr[lo]
pivot_idx = random.randint(lo, hi)
arr[pivot_idx], arr[hi] = arr[hi], arr[pivot_idx]
pivot = arr[hi]
store = lo
for i in range(lo, hi):
if arr[i] < pivot:
arr[store], arr[i] = arr[i], arr[store]
store += 1
arr[store], arr[hi] = arr[hi], arr[store]
# store 是 pivot 最终位置
# 如果 store == hipivot 是当前区间最大值
if store == hi:
return arr[store]
# 否则在 store+1..hi 中继续找(右侧都 >= pivot
return _quickselect_max(arr, store + 1, hi)