What is the complexity of this simple piece of code?

前端 未结 10 1264
遇见更好的自我
遇见更好的自我 2020-11-29 04:28

I\'m pasting this text from an ebook I have. It says the complexity if O(n2) and also gives an explanation for it, but I fail to see how.

Question: What i

10条回答
  •  情歌与酒
    2020-11-29 05:11

    That really depends on the implementation of StringBuffer. Supposing .append() was constant time, it's clear that you have an O(n) algorithm in time where n = length of the words array. If .append isn't constant time, you'll need to multiple your O(n) by the time complexity of the method. If indeed the current implementation of StringBuffer copies strings character-by-character, then the algorithm above is

    Θ(n*m), or O(n*m), where n is the number of words and m is average word length, and your book is wrong. I assume you're looking for a strict bound.

    Simple example that the book's answer is incorrect: String[] words = ['alphabet'] By the book's definition, n=8, so the algorithm will be bounded by 64 steps. Is this the case? Clearly not strictly. I see 1 assignment and 1 copy operation with n characters, so you get about 9 steps. This sort of behavior is predicted by the bounds of O(n*m), as I illustrated above.

    I did some digging, and this clearly isn't a simple character copy. It looks like memory is being copied in bulk, which puts us back at O(n), your first guess at the solution.

    /* StringBuffer is just a proxy */
    public AbstractStringBuilder append(String str) 
    {
            if (str == null) str = "null";
            int len = str.length();
            ensureCapacityInternal(count + len);
            str.getChars(0, len, value, count);
            count += len;
            return this;
    }
    
    /* java.lang.String */
    void getChars(char dst[], int dstBegin) {
                 System.arraycopy(value, offset, dst, dstBegin, count);
    }
    

    Your book is either old, terrible, or both. I'm not determined enough to dig through JDK versions to find a less optimal implementation of StringBuffer, but perhaps one exists.

提交回复
热议问题