算法----查找列表中元素的最小值和最大值

复制代码
#第一种:分组计算
class MaxMin():
    def __init__(self):
        self.max = None
        self.min = None

    def getMax(self):
        return self.max

    def getMin(self):
        return self.min

    def _update_value(self, value, current_value, is_max):
        """
        辅助方法,用于更新最大或最小值。

        参数:
        value (int/float): 待比较的值。
        current_value (int/float): 当前的最大或最小值。
        is_max (bool): 如果为True,表示更新最大值;如果为False,表示更新最小值。

        返回:
        int/float: 更新后的最大或最小值。
        """
        if is_max:
            return max(value, current_value)
        return min(value, current_value)

    def GetmaxAndMin(self, arr):
        if arr is None:
            print("参数不合法!")
            return

        self.max = arr[0]
        self.min = arr[0]

        # 两两一组进行比较交换
        for i in range(0, len(arr) - 1, 2):
            if arr[i] > arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]

        # 更新最小值
        for i in range(0, len(arr), 2):
            self.min = self._update_value(arr[i], self.min, False)

        # 更新最大值
        for i in range(1, len(arr), 2):
            self.max = self._update_value(arr[i], self.max, True)

        # 处理列表长度为奇数的情况
        if len(arr) % 2 == 1:
            self.min = self._update_value(arr[-1], self.min, False)
            self.max = self._update_value(arr[-1], self.max, True)


if __name__ == "__main__":
    array = [7, 3, 19, 40, 4, 7, 1]
    m = MaxMin()
    m.GetmaxAndMin(array)
    print("max=" + str(m.getMax()))
    print("min=" + str(m.getMin()))
复制代码
# 第二种:选择最大最小元素
def selectMaxMin(a,low,high):
    if high-low<=1:
        max_=max(a[high],a[low])
        min_=min(a[high],a[low])
        return max_,min_
    max_L,min_L=selectMaxMin(a,low,low+(high-low)//2)
    max_R,min_R=selectMaxMin(a,low+(high-low)//2+1,high)
    return max(max_L,max_R),min(min_L,min_R)
print(selectMaxMin([1,3,-1,4,9,5,2],0,6))
复制代码
返回结果:

第二种:

相关推荐
段一凡-华北理工大学21 分钟前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化
Ljwuhe29 分钟前
C++——多态
开发语言·c++
心平气和量大福大1 小时前
C#-WPF-Window主窗体
开发语言·c#·wpf
CV-Climber1 小时前
检索技术的实际应用
人工智能·算法
hhzz2 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_3 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸3 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
C^h3 小时前
python函数学习
人工智能·python·机器学习
Fanta丶3 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python
决战灬3 小时前
langgraph之interrupt(理论篇)
人工智能·python·agent