-3

Ques. 1.) I was writing a code to swap two numbers using a temp variable. I don't know how this temp variable will affect the space complexity in this case. Below is the code.

public void swap(int a, int b){
   int temp;
   temp = a;
   a = b;
   b = temp;
}

Ques. 2) How does using these extra variables like temp have an affect on space complexity in any function in general code practice?

grayskull
  • 11
  • 1
  • I think that would be helpful https://stackoverflow.com/questions/36363550/difference-in-space-complexity-of-different-sorting-algorithms – MrFisherman Jan 08 '21 at 16:46
  • 1) How do you solve it *without* the temp variable? 2) Can you give *any* way that adding a new variable does *not* increase space complexity? – Scott Hunter Jan 08 '21 at 16:47
  • 4
    1. The method won't actually swap the variables for the caller. 2. It's `O(1)`. – Unmitigated Jan 08 '21 at 16:47
  • An `int` is around four bytes on typical platforms. Looking at the space impact of the temp variable like an extreme microoptimization at best, unless you're somehow severely memory-constrained. – nanofarad Jan 08 '21 at 16:49
  • @ScottHunter You can use `a ^= b; b ^= a; a^= b;` to swap without a temporary variable. – Unmitigated Jan 08 '21 at 16:51
  • I generally declare temporary / swap variables in the class scope so It gets GC'd when the class gets GC'd. I just reuse the same one over and over for all methods that need it. I have been doing this since forever because I started programming in Pascal/C/C++ and back then it mattered... with 1024k ram and 8mhz processors :) It probably still matters today, only like how that one mosquito you swatted affected the mosquito population in a northern Canadian marsh. –  Jan 08 '21 at 17:10
  • 2
    @RandomCoder_01 that is actually a code smell https://rules.sonarsource.com/java/type/Code%20Smell/RSPEC-1450 . And the space used by local variable will be almost immediately available for reuse after the method is gone. – dreamcrash Jan 08 '21 at 17:14
  • @RSPEC-1450 good point! (And great site!) –  Jan 08 '21 at 17:20

1 Answers1

1

General Answer: No, this does neither affect space- nor time-complexity

Space complexity is to declare, how how much space is used, when the algorithm has to process a lot (converging to infinity) of data. Since this temp variable is just used in the scope of this method, this would not affect the space in a space-complexity manner.

This article explains the topic quite good => https://www.baeldung.com/cs/space-complexity

novarx
  • 498
  • 3
  • 6