Algorithmic complexity of naive code for processing all consecutive subsequences of a list: n^2 or n^3?

前端 未结 9 1128
傲寒
傲寒 2020-12-25 11:41

I\'m studying for a test and found this question:

I can\'t really determine the complexity, I figured it\'s either O(n2) or O(n3) and I\'m lea

9条回答
  •  青春惊慌失措
    2020-12-25 12:10

    If you do not feel well-versed enough in the underlying theory to directly apply @MohamedEnnahdiElIdri's analysis, why not simply start by testing the code?

    Note first that the loop boundaries only depend on the array's length, not its content, so regarding the time complexity, it does not matter what the algorithm does. You might as well analyse the time complexity of

    public static long countwhat(int length) {
      long count = 0;
      for (int i = 0; i < length; i++) {
        for (int j = i; j < length; j++) {
          for (int k = i + 1; k <= j; k++) {
            count++;
          }
        }
      }
      return count;
    }
    

    Looking at this, is it easier to derive a hypothesis? If not, simply test whether the return value is proportional to length squared or length cubed...

    public static void main(String[] args) {
      for (int l = 1; l <= 10000; l *= 2) {
        long count = countwhat(l);
        System.out.println("i=" + l + ", #iterations:" + count + 
          ", #it/n²:" + (double) count / l / l +
          ", #it/n³:" + (double) count /  l / l / l);
      }
    }
    

    ... and notice how one value does not approach anyconstant with rising l and the other one does (not incidentally the very same constant associated with the highest power of $n$ in the methodological analysis).

提交回复
热议问题