I have started learning Big O notation and analysing time complexities, and I tried messing around with some code to try and understand its time complexity. Here's one of the lines that I had, but I can't seem to figure out what the time complexity for the sum method is? I reckon it is o(n^3) but my friend says it should be o(n^2). Any insights as to what is the right answer?
public static double sum(double[] array) { double sum = 0.0; for(int k = 0; k < size(array); k++) sum = sum + get(array, k); return sum; } public static double get(double[] array, int k) { for(int x=0; x < k; x++) if(x==k) return array[k]; return -1; } public static int size(double[] array) { int size = 0; for(int k=0; k<array.length; k++) size++; return size; }
size()is O(n);get()isO(n). You are executingsize()on each iteration of a loop which runssize()times; and inside the loop you executeget()on each iteration. So it's O(n^3).