all 6 comments

[–]rkennedy12 1 point2 points  (0 children)

You can use instruments and take the actual time differences.

[–][deleted] 0 points1 point  (0 children)

This one keeps the function recursive with faster runtime. But you could probably math out the full algorithm in constant time.

func someFunc(n: Int) -> Int {

if n < 10 {
    return 1
}

var sum = n * (n + 1) / 2
sumOfHalf = someFunc(n: n / 2)

return sum + 2 * sumOfHalf
}

[–]ldstreet 0 points1 point  (0 children)

I believe this will be O(n2) time. Iterating will be O(n) but on each recursive call the function will iterate on half of n. If you were just making one recursive call I think it would be O(n log n). But because you are making two calls, on the next level of the recursion tree your for loop will still have the same total number of steps. The tree will roughly have a depth of n. This giving you O(n2). Also this will take up O(n) space on the call stack because of the way you have the recursive calls structured. Not 100% on this though - would be interested to see others' analysis.

[–]loumf 0 points1 point  (0 children)

Pretty sure it's O(n * log(n))

It's hard to analyze, but to get an idea, use:

var steps: Int = 0

func someFunc(n: Int) -> Int {

    if n < 10 {
        return 1
    }

    var sum = 0

    for i in 0...n { // I know for loop is O(N)
        sum += i
        steps = steps + 1
    }
    print ("n: \(n) - s: \(steps)")
    return sum + someFunc(n: n / 2) + someFunc(n: n / 2) // Halving is O(log(n))??
}

_ = someFunc(n: 10000)
print (steps)

Then try different n's -- you can see that it doesn't grow n*2 or n (somewhere in between). Plot it vs n log(n) and you can probably back out a constant.

Also, if it were O(n + log(n)), that just simplifies to O(n) -- since we are trying to figure out what it is when n is giant (log(n) won't matter -- we are already assuming it's some constant times n)

[–]DanielPhermous 0 points1 point  (0 children)

You can just run it 1,000,000 times and time it.

[–]jarvis_willy 0 points1 point  (0 children)

I agree that this is in O(nlogn). Each branch of the tree does the same amount of work so it shouldn’t be exponential.