python---顺序查找,二分查找

比较熟悉了。

但要注意细节,

二分查找时,普通方法mid处理,递归时,mid处理。

# coding = utf-8


def sequential_search(a_list, item):
    pos = 0
    found = False
    while pos < len(a_list) and not found:
        if a_list[pos] == item:
            found = True
        pos += 1
    return found


print('===========顺序查找==========')
test_list = [1, 2, 32, 8, 17, 10, 42, 13, 0]
print(sequential_search(test_list, 3))
print(sequential_search(test_list, 13))


def ordered_sequential_search(a_list, item):
    pos = 0
    stop = False
    found = False
    while pos < len(a_list) and not found and not stop:
        if a_list[pos] == item:
            found = True
        if a_list[pos] > item:
            stop = True
        pos += 1
    return found


print('===========已排序顺序查找==========')
test_list = [1, 2, 32, 33, 47, 53, 62, 73, 90]
print(ordered_sequential_search(test_list, 32))
print(ordered_sequential_search(test_list, 13))


'''
def binary_search(a_list, item):
    begin = 0
    end = len(a_list) - 1
    found = False
    while begin <= end and not found:
        mid = (begin + end) // 2
        if a_list[mid] > item:
            end = mid - 1
        elif a_list[mid] < item:
            begin = mid + 1
        else:
            found = True
    return found
'''


def binary_search(a_list, item):
    if len(a_list) == 0:
        return False
    else:
        mid = len(a_list) // 2
        if a_list[mid] > item:
            return binary_search(a_list[:mid], item)
        elif a_list[mid] < item:
            return binary_search(a_list[mid+1:], item)
        else:
            return True


print('===========二分查找==========')
test_list = [1, 2, 32, 33, 47, 53, 62, 73, 90]
print(binary_search(test_list, 32))
print(binary_search(test_list, 13))

  

C:\Users\Sahara\.virtualenvs\test\Scripts\python.exe C:/Users/Sahara/PycharmProjects/test/python_search.py
===========顺序查找==========
False
True
===========已排序顺序查找==========
True
False
===========二分查找==========
True
False

Process finished with exit code 0

  

转载于:https://www.cnblogs.com/aguncn/p/10679593.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值