The order of the body statements of a given algorithm is very important in determining Big-O of the algorithm.

Example: Find Big-O of the following algorithm

1.
```cpp
for (int i = 1; i < n; i++) {
sum = sum + i;
}
```
[tex]\[ T(n) = 2 \times n = 2n = O(n) \][/tex]

2.
```cpp
for (int i = 1; i < n; i++) {
for (int j = 1; j <= i; j++) {
k++;
}
}
```



Answer :

To determine the Big-O notation (time complexity) of the given two algorithms, we need to analyze the loops and the number of operations performed in each loop. Let's break it down step-by-step:

### Algorithm 1:

1. Loop Analysis:
- The loop runs from [tex]\(i = 1\)[/tex] to [tex]\(i < n\)[/tex], i.e., it iterates [tex]\(n - 1\)[/tex] times. However, in Big-O notation, we drop the constant terms, so we will consider this as iterating [tex]\(n\)[/tex] times.
- Inside the loop, there's a single operation: `sum = sum + i`.

2. Operation Count:
- Each iteration of the loop performs a constant time operation (addition), which takes [tex]\(O(1)\)[/tex] time.
- Since the loop runs [tex]\(n\)[/tex] times, the total time complexity is [tex]\(O(n) \cdot O(1) = O(n)\)[/tex].

Therefore, the time complexity of the first algorithm is [tex]\(O(n)\)[/tex].

### Algorithm 2:

1. Outer Loop Analysis:
- The outer loop runs from [tex]\(i = 1\)[/tex] to [tex]\(i < n\)[/tex], i.e., it iterates [tex]\(n - 1\)[/tex] times. Again, we consider it as iterating [tex]\(n\)[/tex] times for Big-O notation.

2. Inner Loop Analysis:
- The inner loop runs from [tex]\(j = 1\)[/tex] to [tex]\(j \leq i\)[/tex]. For each iteration of the outer loop, the inner loop runs proportionally to the value of [tex]\(i\)[/tex]:
- When [tex]\(i = 1\)[/tex]: The inner loop runs [tex]\(1\)[/tex] time.
- When [tex]\(i = 2\)[/tex]: The inner loop runs [tex]\(2\)[/tex] times.
- ...
- When [tex]\(i = n\)[/tex]: The inner loop runs [tex]\(n\)[/tex] times.

3. Total Iterations:
- The total work done by the inner loop across all iterations of the outer loop can be calculated as the sum of the first [tex]\(n\)[/tex] integers:
[tex]\[ 1 + 2 + 3 + \ldots + n = \frac{n(n + 1)}{2} \][/tex]
- The sum [tex]\(\frac{n(n + 1)}{2}\)[/tex] is a quadratic expression in terms of [tex]\(n\)[/tex], and when we analyze its growth rate for large [tex]\(n\)[/tex], it simplifies to [tex]\(O(n^2)\)[/tex].

Therefore, the time complexity of the second algorithm is [tex]\(O(n^2)\)[/tex].

### Summary:
- The time complexity of the first algorithm is [tex]\(O(n)\)[/tex].
- The time complexity of the second algorithm is [tex]\(O(n^2)\)[/tex].