在线性搜索中获得算法效率

时间:2015-11-22 05:34:01

标签: python algorithm

对于未排序列表上的简单线性搜索,我的教科书说明如下:

要确定平均情况,请添加在每个可能位置查找目标所需的迭代次数,并将总和除以n。因此,该算法执行(n + n - 1 + n -2 + ... + 1)/ n或(n + 1)/ 2次迭代。

他使用的代码示例如下:

def sequentialSearch(target, lyst):
    """Returns the position of the target item if found, or -1 otherwise."""
    position = 0
    while position < len(lyst):
        if target == lyst[position]:
            return position
        position += 1
    return False

我无法理解他是如何从上面得出(n + 1)/ 2的?

1 个答案:

答案 0 :(得分:3)

当您遍历列表以获取可能的目标时,您可能需要n,n-1,...2,1尝试找到它。所以,如果你想找到平均案例。它只是将它们全部加起来并除以n。 (n+n-1+...+2+1)/n。我们知道(n+n-1+...+2+1) = n(n+1)/2。因此,我们得到n(n+1)/2*n的答案,(n+1)/2作为平均案例。

e.g。用于线性搜索

 lyst = [4,5,2,1,6]
 possibilities of targets = 4 or 5 or 2 or 1 or 6
 target = 4
 attemps reqd = 1 as found in first attempt i.e first location
 lyst = [4,5,2,1,6]
 target = 5
 attemps reqd = 2 as found in second attempt i.e second location
 lyst = [4,5,2,1,6]
 target = 2
 attemps reqd = 3 as found in third attempt i.e third location
 lyst = [4,5,2,1,6]
 target = 1
 attemps reqd = 4 as found in fourth attempt i.e fourth location
 lyst = [4,5,2,1,6]
 target = 6
 attemps reqd = 5 as found in fifth attempt i.e fifth location

 sum of all attempts reqired = 1 + 2 + 3 + 4 + 5 = 15 
 same as n(n+1)/2 = 5(5+1)/2 = 5*3 = 15

 avg case = (1+2+3+4+5)/n = 15/5 = 3
 same as n(n+1)/2*n = 5(6)/2*5 = (n+1)/2 = 6/2 = 3

平均值表示所有元素的总和除以元素数。