简体   繁体   English

平均时间复杂度

[英]Average Time Complexity

I have a recursive function as you can see from below. 从下面可以看到,我有一个递归函数。 I also have the iterative version of same function. 我也有相同功能的迭代版本。 My problem is about recursive function's time complexity. 我的问题是关于递归函数的时间复杂度。 Based on my knowledge it should be O(n^2). 根据我的知识,它应该是O(n ^ 2)。 What is the time complexity of this function? 该函数的时间复杂度是多少? If it is O(n^2); 如果是O(n ^ 2); I test two functions(iterative-recursive) with same input why is there a huge difference between running times? 我用相同的输入测试两个函数(迭代递归),为什么运行时间之间有巨大差异? Thank you 谢谢

Time Difference For Iterative :4.045395 Time Difference For Recursive :20.554156 迭代时差:4.045395递归时差:20.554156

def naive_dac(arr):
    if len(arr) == 1:
        return 0

    count = naive_dac(list(arr[0:len(arr) - 1]))
    for i in range(0,len(arr)):
        if int(arr[i]) > int(arr[len(arr) - 1]):
            count += 1
    return count

Iterative version 迭代版

def brute_force(arr):
    count = 0
    for i in range(0,len(arr)):
        for j in range(i,len(arr)):
            if arr[j] < arr[i]:
                count += 1
    return count

I don't fully understand the recursive version but I think the problem is this line: 我不完全了解递归版本,但我认为问题是此行:

count = naive_dac(list(arr[0:len(arr) - 1]))

Every time you call the recursive function you are creating a copy of your list and this operation is time consuming. 每次调用递归函数时,您都在创建列表的副本,此操作非常耗时。 Depending on the size of the list this can affect drastically the algorithm's performance. 根据列表的大小,这可能会严重影响算法的性能。 Is really necessary to create a copy? 真的有必要创建副本吗?

Assuming that your algorithm is correct and as you don't modify the list you can use a variable to store the length of the list. 假设您的算法正确并且不修改列表,则可以使用变量存储列表的长度。

def naive_dac(arr, length):
    if length == 1:
        return 0

    count = naive_dac(arr, length - 1)
    for i in range(0, length):
        if arr[i] > arr[length-1]:
            count += 1
    return count

EDIT : The extra overhead was caused by the castings: int(arr[i]) ... . 编辑 :额外的开销是由强制转换引起的: int(arr[i]) ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM