173k views
5 votes
What is the worst case run time of: int sum(int[] a) { int s = 0; for (int i : a) { s += i; } return s; }

1 Answer

4 votes

Final answer:

The worst case run time of the function to sum elements of an array is O(n), which means it increases linearly as the number of elements in the array increases.

Step-by-step explanation:

The worst case run time of the given function int sum(int[] a) which calculates the sum of all the elements in an array can be determined by analyzing the for loop inside the function. The worst case run time of the function to sum elements of an array is O(n), which means it increases linearly as the number of elements in the array increases.

Since the loop iterates over each element of the array exactly once, and the operation inside the loop (s += i) is a constant time operation, the worst case run time complexity is O(n), where n is the number of elements in the array.

Therefore, if the array has a large number of elements, the time it takes the function to run will increase linearly with the number of elements.

User Sirmabus
by
9.1k points