搜索算法 -- 搜索最小值、顺序搜索、二分(叉)搜索

1. 搜索最小值

首先python的min函数可以返回列表的最小项,我们想研究一下它的时间复杂度,代码如下:

def minIndex(lyst):
    min_index = 0
    current_index = 1
    while current_index < len(lyst):
        if lyst[current_index] < lyst[min_index]:
            min_index = current_index
        current_index += 1  # 这句卸载if循环外说明,只要不碰到比min_index小的,current_index都不会向后移动;换句话说,每次最小值搜索,可能要遍历整个列表
    return min_index

lyst = [1, 2, 3, 4, 7, 6]
print(minIndex(lyst))  # 返回的是最小值的索引,所以运行结果是0

 

2. 顺序/线性搜索一个列表

python的in运算符作为list类中名为__contains__的一个方法而实现。该方法在列表(任意排列)中搜索特定的项。

如下是一个搜索函数的代码,时间复杂度最好情况是O(1), 其他情况为O(n)

def sequentialSearch(target, lyst):
    index = 0
    while index < len(lyst):  # 索引到最后一项,与目标值比较
        if target == lyst[index]:
            return index
        index += 1
    return -1  # 如果搜索不到与目标项相等的,返回-1

import random
lyst = []
for count in range(5):
    lyst.append(random.randint(1, 21))  # 5个[1, 21]之间的随机数组成的列表
print(lyst)
print(sequentialSearch(10, lyst))  # 搜到10,就返回目标项在列表的索引,搜不到就返回-1

 

3. 有序列表的二叉搜索

当搜索的目标项不在列表中时,会发生最坏情况,就是要二分到只剩一项,时间复杂度为O(log2n)

def binarysearch(target, sortedlyst):  # 要搜索的目标项作为函数的形参,由调用函数时的实参传入
    left = 0
    right = len(lyst) - 1
    while left <= right - 1:
        midpoint = (left + right) // 2
        if target == sortedlyst[midpoint]:
            return midpoint
        elif target < sortedlyst[midpoint]:  # 如果目标项小于当前项,算法搜索中间位置以前的部分(左列表)
            right = midpoint - 1  # 因此由中间位置分开后的左列表,其右端是midpoint的前一项
        else:
            left = midpoint + 1
    return -1

import random
lyst = []
for count in range(5):
    lyst.append(random.randint(1, 21))  # 5个[1, 21]之间的随机数组成的列表
sortedlyst = sorted(lyst)  # 因为二分法要求输入一个排序好的列表,这里仅用python内置函数对其排序
print(sortedlyst)
print(binarysearch(10, sortedlyst))  # 搜到10,就返回目标项在列表的索引,搜不到就返回-1

 

posted on 2019-02-26 12:31  fly&飞  阅读(457)  评论(0)    收藏  举报