0

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; } 
1
  • size() is O(n); get() is O(n). You are executing size() on each iteration of a loop which runs size() times; and inside the loop you execute get() on each iteration. So it's O(n^3). Commented Oct 26, 2021 at 12:54

1 Answer 1

1

I guess you friend is right, time complexity is O(n^2). Because on each iteration in your loop, you consequently calculate size(), which is order of O(n), and calculate get(), which on average is O(n/2). So each iteration's complexity is O(1.5 * n) and overall is O(n^2)

Sign up to request clarification or add additional context in comments.

2 Comments

You said get is on average O(n/2), but if we are looking at worst case scenario, would it still be O(n^2)? Or am I confusing the concepts here?
So for get the worst call would be that of k = n - 1 and best would be n = 0, but usullly we just take the average which is n/2.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.