big o notation practice c++
Big O Notation Practice in C++
Consider the following C++ code:
int sum(int arr[], int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += arr[i];
}
return total;
}
- Step 1: Identify the Operations
The function performs a single addition operation inside the loop, and the loop itself runs n times.
Step 2: Express the Time Complexity
The time complexity of the function can be expressed as O(n), where n is the size of the input array.
Step 3: Justification
The loop iterates through the entire input array, performing a constant-time operation (addition) at each iteration. As the number of elements in the input array increases, the number of iterations increases linearly, resulting in a linear time complexity of O(n).
Conclusion
- The time complexity of the
sum
function is O(n), indicating that its runtime grows linearly with the size of the input array.