Input:
5
Output:
5
4
3
2
1
package jan27;
public class PrintDecreasing {
public static void main(String[] args) {
int n = 5;
printDecreasing(n);
}
/**
* Prints numbers from n down to 1 using recursion.
* <p>
* Time Complexity: O(n)
* - Each recursive call processes one value of n and makes a single recursive call,
* resulting in n calls until the base case (n == 0) is reached.
* <p>
* Space Complexity: O(n)
* - The call stack holds n function calls (from n to 1) before unwinding,
* so space used is proportional to the depth of recursion.
*/
private static void printDecreasing(int n) {
if (n == 0) // base case
return;
System.out.println(n); // work
printDecreasing(n - 1); // recursive call (faith)
}
}
✅ Time and Space Complexity Table
| Case | Time Complexity | Space Complexity | Explanation |
|---|---|---|---|
| Best | O(n) | O(n) | Function calls from n down to 1; recursion depth = n |
| Average | O(n) | O(n) | All recursive calls executed once; linear stack usage |
| Worst | O(n) | O(n) | In all cases, recursion proceeds to base case (n == 0) |
No comments:
Post a Comment