Hi i am having a problem with this im dont really understand
Hi i am having a problem with this im don\'t really understand how runtime works can someone help me with this and also list the steps on how to solve these types problems
Find the running time T( n ) of the calculateSum method from this week\'s lecture video:
public static int calculateSum(int[] numbers) {
int sum = 0;
for(int i=0; i<numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
Note that you are finding the running time, not the order of growth. We already know the order of growth is O( n ).
List the steps leading to your calculation in case your answer is wrong but could get partial credit.
Count all operations, including loop controls, declarations, and updates.
i++ should be considered two statements (an addition and assignment)
Hint: re-write using \"statement1, statement2, etc.\" as shown in the reading for this week.
Solution
public static int calculateSum(int[] numbers) {
int sum = 0; // this takes constant time : O(1)
for(int i=0; i<numbers.length; i++) { // this loop runs n time : i = 0 to length-1 : O(n)
sum = sum + numbers[i]; // this takes constant time: O(1)
}
return sum; // this takes constant time : O(1)
}
So, running time : O(n) + O(1) = O(n)
Please let me know in case of any issue
