Question

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). What is the time complexity of this function? If it is 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

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
Was it helpful?

Solution

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]) ....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top