24大数据 15-2 线性查找和选择排序

15-2 12.11

python 复制代码
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid  # 找到了,返回索引
        elif arr[mid] < target:
            left = mid + 1  # 目标在右边
        else:
            right = mid - 1  # 目标在左边
    return -1  # 返回-1表示没找到

test_list = [1, 3, 5, 7, 9, 11, 13, 15]
print("查找7的位置:", binary_search(test_list, 7))  # 应该返回3
print("查找9的位置:", binary_search(test_list, 9))  # 应该返回4
print("查找8的位置:", binary_search(test_list, 8))  # 应该返回-1
'''
线性查找
线性查找指按一定的顺序从头开始检查数组中每一个元素,
直到找到所要寻找的特定值为止。
'''
def search(arr, n, x):
    for i in range(0, n):
        if (arr[i] == x):
            return i
    return -1
# 在数组 arr 中查找字符 D
arr = ['A', 'B', 'C', 'D', 'E']
x = 'D'
n = len(arr)
result = search(arr, n, x)
if (result == -1):
    print("元素不在数组中")
else:
    print("元素在数组中的索引为", result)

'''
选择排序
工作原理:首先在未排序序列中找到最小(大)元素,
存放到排序序列的起始位置。
然后,再从剩余未排序元素中继续寻找最小(大)元素,
然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
'''
def paixu(shuzu):
    qi=[]
    while len(shuzu)>0:
        qi.append(max(shuzu))
        shuzu.remove(max(shuzu))
    return qi
luan=[90,50,26,98,45,21,26,2,87,51]
print(f"已排好序,顺序为{paixu(luan)}")
相关推荐
吴佳浩9 小时前
GPU 编号进阶:CUDA\_VISIBLE\_DEVICES、多进程与容器化陷阱
人工智能·pytorch·python
全栈凯哥9 小时前
18.Python中的导入类完全指南
python
sunwenjian88610 小时前
Java进阶——IO 流
java·开发语言·python
guts35010 小时前
图像篡改数据集下载:COVERAGE、CASIA
python·数据集
森林猿11 小时前
java-modbus-读取-modbus4j
java·网络·python
2401_8796938711 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
chushiyunen11 小时前
python chatTts实现tts文本转语音、音频
python
FreakStudio11 小时前
把 Flask 搬进 ESP32,高中生自研嵌入式 Web 框架 MicroFlask !
python·单片机·嵌入式·cortex-m3·异步编程·电子diy
love530love12 小时前
OpenClaw 手机直连配置全流程
人工智能·windows·python·智能手机·c#·agent·openclaw
chushiyunen12 小时前
python中的内置属性 todo
开发语言·javascript·python