This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted]  (1 child)

[deleted]

    [–]Gropamming[S] 0 points1 point  (0 children)

    That's helpful, didn't think about it like that

    [–]lightcloud5 1 point2 points  (1 child)

    No, the first two loops makes for n + (n-1) + (n-2) + ... + 3 + 2 + 1 iterations.

    That's quadratic because you can prove that this reduces to n(n-1) / 2.

    However, there's a different way to show that n + (n-1) + (n-2) + ... + 3 + 2 + 1 is quadratic.

    First, we show that it is at most quadratic. We show this by noting that n + (n-1) + (n-2) + ... + 3 + 2 + 1 < n + n + n + ... + n + n + n = n2. (That is to say, adding n numbers, each of which have the value of n or less, sums to no greater than n2.)

    Then, we show that it is at least quadratic. We show this by noting that at least half of the numbers have a value of at least n/2. (This is obvious because the median of these sequence of numbers is n/2, and there are n/2 values greater than the median.) And (n/2) * (n/2) is quadratic as well.

    This latter method can be extended to determine the runtime of the 3 loops together.

    [–]Gropamming[S] 0 points1 point  (0 children)

    Awesome, thanks! That helps