Theta(n ** 2)和Theta(n * lgn)算法执行不正确

时间:2012-12-09 17:41:38

标签: python algorithm python-2.7

我正在阅读算法简介并尝试完成本书中的练习。

在练习4.1-3中

  
    

4.1-3     在您自己的计算机上实现最大子阵列问题的强制算法和递归算法。问题大小n0给出了交叉     递归算法胜过强力算法的点?然后,     更改递归算法的基本情况以使用强力算法     每当问题大小小于n0时。这会改变交叉点吗?

  

我根据本书的伪代码编写了两种算法。但是,我的代码肯定有问题,因为第二个,设计为Theta(n * lgn)并且应该运行得更快,总是比第一个Theta(n ** 2)运行得慢。我的代码如下所示。


def find_maximum_subarray_bf(a):        #bf for brute force
    p1 = 0
    l = 0           # l for left
    r = 0           # r for right
    max_sum = 0
    for p1 in range(len(a)-1):
        sub_sum = 0
        for p2 in range(p1, len(a)):
            sub_sum += a[p2]
            if sub_sum > max_sum:
                max_sum  = sub_sum
                l = p1
                r = p2
    return l, r, max_sum

def find_maximum_subarray_dc(a):        #dc for divide and conquer

    # subfunction
    # given an arrary and three indics which can split the array into a[l:m]
    # and a[m+1:r], find out a subarray a[i:j] where l \leq i \less m \less j \leq r".
    # according to the definition above, the target subarray must
    # be combined by two subarray, a[i:m] and a[m+1:j]
    # Growing Rate: theta(n)

    def find_crossing_max(a, l, r, m):

        # left side
        # ls_r and ls_l indicate the right and left bound of the left subarray.
        # l_max_sum indicates the max sum of the left subarray
        # sub_sum indicates the sum of the current computing subarray      
        ls_l = 0
        ls_r = m-1
        l_max_sum = None
        sub_sum = 0
        for j in range(m+1)[::-1]:      # adding elements from right to left
            sub_sum += a[j]
            if sub_sum > l_max_sum:
                l_max_sum = sub_sum
                ls_l = j

        # right side
        # rs_r and rs_l indicate the right and left bound of the left subarray.
        # r_max_sum indicates the max sum of the left subarray
        # sub_sum indicates the sum of the current computing subarray                
        rs_l = m+1
        rs_r = 0
        r_max_sum = None
        sub_sum = 0
        for j in range(m+1,len(a)):
            sub_sum += a[j]
            if sub_sum > r_max_sum:
                r_max_sum = sub_sum
                rs_r = j

        #combine
        return (ls_l, rs_r, l_max_sum+r_max_sum)

    # subfunction
    # Growing Rate: should be theta(nlgn), but there is something wrong
    def recursion(a,l,r):           # T(n)
        if r == l:
            return (l,r,a[l])
        else:
            m = (l+r)//2                    # theta(1)
            left = recursion(a,l,m)         # T(n/2)
            right = recursion(a,m+1,r)      # T(n/2)
            crossing = find_crossing_max(a,l,r,m)   # theta(n)

            if left[2]>=right[2] and left[2]>=crossing[2]:
                return left
            elif right[2]>=left[2] and right[2]>=crossing[2]:
                return right
            else:
                return crossing

    #back to master function
    l = 0
    r = len(a)-1
    return recursion(a,l,r)

if __name__ == "__main__":

    from time import time

    a = [100,-10,1,2,-1,4,-6,2,5]
    a *= 2**10

    time0 = time()
    find_maximum_subarray_bf(a)
    time1 = time()
    find_maximum_subarray_dc(a)
    time2 = time()
    print "function 1:", time1-time0
    print "function 2:", time2-time1 
    print "ratio:", (time1-time0)/(time2-time1)

1 个答案:

答案 0 :(得分:5)

首先,蛮力中的一个错误:

for p1 in range(len(a)-1):

应该是range(len(a)) [或xrange],因为它找不到[-12,10]的最大子数组。

现在,递归:

def find_crossing_max(a, l, r, m):

    # left side
    # ls_r and ls_l indicate the right and left bound of the left subarray.
    # l_max_sum indicates the max sum of the left subarray
    # sub_sum indicates the sum of the current computing subarray      
    ls_l = 0
    ls_r = m-1
    l_max_sum = None
    sub_sum = 0
    for j in range(m+1)[::-1]:      # adding elements from right to left

您正在检查所有索引为0,但您应该只检查l的索引。不要构建range列表并将其反转,而是使用xrange(m,l-1,-1)

        sub_sum += a[j]
        if sub_sum > l_max_sum:
            l_max_sum = sub_sum
            ls_l = j

对于右边的总和,模拟成立,你应该只检查指数到r,所以xrange(m+1,r+1)

此外,您的总和的初始值分别为。最大子阵列的索引对于左侧部分是可疑的,而对于右侧则是错误的。

对于左侧部分,我们从空的开头开始,但必须包含a[m]。这可以通过最初设置l_max_sum = None或设置l_max_sum = a[m]并让j省略索引m来完成。无论哪种方式,ls_l的初始值不应为0,而对于ls_r,它不应为m-1。如果ls_r的初始值为m,则ls_l必须为m+1l_max_sum应为Nonem如果l_max_suma[m]开头。

对于正确的部分,r_max_sum必须从0开始,rs_r最好以m开头(虽然这不是很重要,但它只会给你错误的索引)。如果右边的总和都不是非负的,那么正确的总和应该是0而不是最大的负数。

recursion中,我们在

中有一些重复
left = recursion(a,l,m)         # T(n/2)

包括a[m]在内的总和已在find_crossing_max中得到处理或主要处理,因此可能

left = recursion(a,l,m-1)

但是人们还必须在r < l中处理recursion的可能性,并且重复很小,所以我会放弃。

由于您始终遍历find_crossing_max中的整个列表,并且称为O(n)次,因此您的分而治之实施实际上也是O(n²)

如果find_crossing_max中选中的范围仅限于[l,r],则您对2^k n/2^k,{{{{{{ 1}},总费用为0 <= k <= log_2 n

通过这些更改(以及一些随机数组生成),

O(n*log n)

我们得到了我们应该期待的东西:

def find_maximum_subarray_bf(a):        #bf for brute force
    p1 = 0
    l = 0           # l for left
    r = 0           # r for right
    max_sum = 0
    for p1 in xrange(len(a)):
        sub_sum = 0
        for p2 in xrange(p1, len(a)):
            sub_sum += a[p2]
            if sub_sum > max_sum:
                max_sum  = sub_sum
                l = p1
                r = p2
    return l, r, max_sum

def find_maximum_subarray_dc(a):        #dc for divide and conquer

    # subfunction
    # given an arrary and three indices which can split the array into a[l:m]
    # and a[m+1:r], find out a subarray a[i:j] where l \leq i \less m \less j \leq r".
    # according to the definition above, the target subarray must
    # be combined by two subarray, a[i:m] and a[m+1:j]
    # Growing Rate: theta(n)

    def find_crossing_max(a, l, r, m):

        # left side
        # ls_r and ls_l indicate the right and left bound of the left subarray.
        # l_max_sum indicates the max sum of the left subarray
        # sub_sum indicates the sum of the current computing subarray      
        ls_l = m+1
        ls_r = m
        l_max_sum = None
        sub_sum = 0
        for j in xrange(m,l-1,-1):      # adding elements from right to left
            sub_sum += a[j]
            if sub_sum > l_max_sum:
                l_max_sum = sub_sum
                ls_l = j

        # right side
        # rs_r and rs_l indicate the right and left bound of the left subarray.
        # r_max_sum indicates the max sum of the left subarray
        # sub_sum indicates the sum of the current computing subarray                
        rs_l = m+1
        rs_r = m
        r_max_sum = 0
        sub_sum = 0
        for j in range(m+1,r+1):
            sub_sum += a[j]
            if sub_sum > r_max_sum:
                r_max_sum = sub_sum
                rs_r = j

        #combine
        return (ls_l, rs_r, l_max_sum+r_max_sum)

    # subfunction
    # Growing Rate:  theta(nlgn)
    def recursion(a,l,r):           # T(n)
        if r == l:
            return (l,r,a[l])
        else:
            m = (l+r)//2                    # theta(1)
            left = recursion(a,l,m)         # T(n/2)
            right = recursion(a,m+1,r)      # T(n/2)
            crossing = find_crossing_max(a,l,r,m)   # theta(r-l+1)

            if left[2]>=right[2] and left[2]>=crossing[2]:
                return left
            elif right[2]>=left[2] and right[2]>=crossing[2]:
                return right
            else:
                return crossing

    #back to master function
    l = 0
    r = len(a)-1
    return recursion(a,l,r)

if __name__ == "__main__":

    from time import time
    from sys import argv
    from random import randint
    alen = 100
    if len(argv) > 1:
        alen = int(argv[1])
    a = [randint(-100,100) for i in xrange(alen)]

    time0 = time()
    print find_maximum_subarray_bf(a)
    time1 = time()
    print find_maximum_subarray_dc(a)
    time2 = time()
    print "function 1:", time1-time0
    print "function 2:", time2-time1 
    print "ratio:", (time1-time0)/(time2-time1)