PowerShell Script to Swap Two Numbers Easily
In PowerShell, swap two numbers using a temporary variable like this:
$temp = $a; $a = $b; $b = $temp.Examples
Inputa=5, b=10
Outputa=10, b=5
Inputa=0, b=0
Outputa=0, b=0
Inputa=-3, b=7
Outputa=7, b=-3
How to Think About It
To swap two numbers, think of holding one number temporarily so it doesn't get lost when you overwrite it. Use a temporary variable to store the first number, then assign the second number to the first, and finally assign the temporary value to the second number.
Algorithm
1
Store the value of the first number in a temporary variable.2
Assign the value of the second number to the first number.3
Assign the value stored in the temporary variable to the second number.4
Print or return the swapped values.Code
powershell
$a = 5 $b = 10 $temp = $a $a = $b $b = $temp Write-Output "After swapping: a=$a, b=$b"
Output
After swapping: a=10, b=5
Dry Run
Let's trace swapping a=5 and b=10 through the code
1
Store first number in temp
$temp = 5
2
Assign second number to first
$a = 10
3
Assign temp to second number
$b = 5
| Variable | Value |
|---|---|
| $temp | 5 |
| $a | 10 |
| $b | 5 |
Why This Works
Step 1: Temporary storage
Using $temp = $a saves the original value of $a so it is not lost.
Step 2: Overwrite first variable
Assigning $a = $b puts the second number into the first variable.
Step 3: Restore second variable
Assigning $b = $temp completes the swap by putting the original first number into the second variable.
Alternative Approaches
Using tuple assignment
powershell
$a = 5 $b = 10 ($a, $b) = @($b, $a) Write-Output "After swapping: a=$a, b=$b"
This method is shorter and uses PowerShell's array unpacking to swap without a temporary variable.
Using arithmetic operations
powershell
$a = 5 $b = 10 $a = $a + $b $b = $a - $b $a = $a - $b Write-Output "After swapping: a=$a, b=$b"
Swaps numbers without extra variables but only works with numeric values and can cause overflow.
Complexity: O(1) time, O(1) space
Time Complexity
Swapping two numbers involves a fixed number of operations, so it runs in constant time O(1).
Space Complexity
Only a few variables are used, so space complexity is constant O(1).
Which Approach is Fastest?
All approaches run in O(1) time; tuple assignment is concise, arithmetic avoids extra variables but has risks.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Temporary variable | O(1) | O(1) | Clear and safe swapping |
| Tuple assignment | O(1) | O(1) | Concise and modern PowerShell |
| Arithmetic operations | O(1) | O(1) | No extra variables but only numeric and safe values |
Use a temporary variable or tuple assignment to swap values clearly and safely.
Forgetting to use a temporary variable causes one value to be overwritten and lost.