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

时间:2022-05-13 15:07:11

比较熟悉了。

但要注意细节,

二分查找时,普通方法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