Search code examples
algorithmtime-complexitypseudocode

why is the complexity O(n^2)?


function F(A :Array){
    i=1
    j=1
    m=0
    c=0
    while i<=Size(A) do
        if A[i]=A[j] then
            c=c+1
        end if
        j=j+1
        if j>Size(A) then
            if c>m then
                m=c
            end if
            c=0
            i=i+1
            j=i
        end if
    end while
return m

I found the first O(n) but can't find the second to they can be O(n^2) thank you for your help


Solution

  • Roughly. In the loop j varies first from i to size of A. Each time j reaches the end i is incremented. Say that n is size of A, you first loop (roughly, don't want to analyse exactly, no need) n times, then n-1, etc. Thus n+n-1+n-2+n-3+...+1, which is n(n+1)2 thus a square of n.