小魚要學數據結構與算法(基於python)—Day11查找和排序之查找

排序和查找

在這裏插入圖片描述

一、知識概覽

本章整體知識點如下:
排序和查找
查找算法知識點如下:
查找知識概覽

二、代碼實現

2.1順序查找

(1)無序表順序查找

# 順序查找
##無序表順序查找
def sequentialSearch(alist, item):
    pos = 0
    found = False
    while pos < len(alist) and not found:
        if alist[pos] == item:
            found = True
        else:
            pos = pos + 1
    return found


testlist = [1, 2, 32, 8, 17, 19, 42, 13]
print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13))

(2)有序表順序查找

# ##有序表查找代碼
def orderedSequentialSearch(alist, item):
    pos = 0
    found = False
    stop = False
    while pos < len(alist) and not found and not stop:
        if alist[pos] == item:
            found = True
        else:
            if alist[pos] > item:
                stop = True
            else:
                pos = pos + 1
    return found


testlist2 = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(orderedSequentialSearch(testlist2, 3))
print(orderedSequentialSearch(testlist2, 13))

2.2 二分法查找

(1)普通二分法

# 二分查找
def binarySearch(alist, item):
    first = 0
    last = len(alist) - 1
    found = False
    while first <= last and not found:
        midpoint = (first + last) // 2
        if alist[midpoint] == item:
            found = True
        else:
            if item < alist[midpoint]:
                last = midpoint - 1
            else:
                first = midpoint + 1
    return found


testlist3 = [0, 1, 2, 8, 13, 17, 19, 32]
print(binarySearch(testlist3, 3))
print(binarySearch(testlist3, 13))

(2)使用遞歸的二分查找
符合分而治之的策略,考慮遞歸法。

# 二分查找遞歸算法版本
def binarySearch2(alist, item):
    # 基本結束條件
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist) // 2
        if alist[midpoint] == item:
            return True
        # 減小規模
        else:
            if item < alist[midpoint]:
                return binarySearch2(alist[:midpoint], item)  # 切片操作複雜度是O(K)
            else:
                return binarySearch2(alist[midpoint + 1:], item)


print(binarySearch2(testlist3, 3))
print(binarySearch2(testlist3, 13))

輸出

False
True
False
True
False
True
False
True

下一節學排序啦~~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章