[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 原有)
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
"""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 == hi,pivot 是当前区间最大值
|
||||
if store == hi:
|
||||
return arr[store]
|
||||
# 否则在 store+1..hi 中继续找(右侧都 >= pivot)
|
||||
return _quickselect_max(arr, store + 1, hi)
|
||||
Reference in New Issue
Block a user