python查找算法

二分查找

# 返回 x 在 arr 中的索引,如果不存在返回 -1
def binarySearch(arr, l, r, x):
    # 基本判断
    if r >= l:

        mid = int(l + (r - l) / 2)

        # 元素整好的中间位置
        if arr[mid] == x:
            return mid

            # 元素小于中间位置的元素,只需要再比较左边的元素
        elif arr[mid] > x:
            return binarySearch(arr, l, mid - 1, x)

            # 元素大于中间位置的元素,只需要再比较右边的元素
        else:
            return binarySearch(arr, mid + 1, r, x)

    else:
        # 不存在
        return -1


# 测试数组
arr = [2, 3, 4, 10, 40]
x = 10

# 函数调用
result = binarySearch(arr, 0, len(arr) - 1, x)

if result != -1:
    print("元素在数组中的索引为 %d" % result)
else:
    print("元素不在数组中")
   # 时间复杂度O(log n)

线性查找(顺序查找)

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)

斐波那契查找

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.runoob.com

# Python 斐波那契数列实现

# 获取用户输入数据
nterms = int(input("你需要几项?"))

# 第一和第二项
n1 = 0
n2 = 1
count = 2

# 判断输入的值是否合法
if nterms <= 0:
    print("请输入一个正整数。")
elif nterms == 1:
    print("斐波那契数列:")
    print(n1)
else:
    print("斐波那契数列:")
    print(n1, ",", n2, end=" , ")
    while count < nterms:
        nth = n1 + n2
        print(nth, end=" , ")
        # 更新值
        n1 = n2
        n2 = nth
        count += 1

插值查找

def binary_search(lis, key):
    low = 0
    high = len(lis) - 1
    time = 0
    while low < high:
        time += 1
        #
        mid = low + int((high - low) * (key - lis[low]) / (lis[high] - lis[low]))
        print("mid=%s, low=%s, high=%s" % (mid, low, high))
        if key < lis[mid]:
            high = mid - 1
        elif key > lis[mid]:
            low = mid + 1
        else:
            #
            print("times: %s" % time)
            return mid
    print("times: %s" % time)
    return False


LIST = [1, 5, 7, 8, 22, 54, 99, 123, 200, 222, 444]
result = binary_search(LIST, 444)
print(result)

代码仅供参考,禁止抄袭

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值