To swap two values, save the first in a temporary variable, assign the second to the first, and then restore the saved value into the second.
A simple example
Exchange two values
Start witha = 1, b = 2
Do thisKeep a copy of the first value
Resulta = 2, b = 1
Save 1, move 2 into a, then move the saved 1 into b. This preserves both original values.
Swap two presentation slots
Start withSlot 1 for Ada, slot 2 for Sam
Do thisExchange the two assignments
ResultSlot 1 for Sam, slot 2 for Ada
Keeping one assignment while moving the other prevents either student from disappearing from the schedule.
Temporary variable
Arithmetic operation
Exclusive OR operation (i.e. XOR)
The arithmetic examples assume the intermediate results fit the numeric type. Multiplication followed by division also requires nonzero divisors. XOR swapping applies to integers stored in distinct variables.
Swap two values with a temporary variable
Kotlin source code
fun main(args: Array<String>) {
var a: Int = 3
var b: Int = 6
println("The value of a before swap is $a")
println("The value of b before swap is $b")
// Swapping of two numbers using temp variable
val temp: Int = a
a = b
b = temp
println("The value of a after swap is $a")
println("The value of b after swap is $b")
}
Output
The value of a before swap is 3
The value of b before swap is 6
The value of a after swap is 6
The value of b after swap is 3
Advertisements
Swap two numbers with addition and subtraction
Kotlin source code
fun main(args: Array<String>) {
var a: Int = 3
var b: Int = 6
println("The value of a before swap is $a")
println("The value of b before swap is $b")
// Swapping of two numbers using arithmetic operations
a = a + b
b = a - b
a = a - b
println("The value of a after swap is $a")
println("The value of b after swap is $b")
}
Output
The value of a before swap is 3
The value of b before swap is 6
The value of a after swap is 6
The value of b after swap is 3
Swap two integers with bitwise XOR
Kotlin source code
fun main(args: Array<String>) {
var a: Int = 3
var b: Int = 6
println("The value of a before swap is $a")
println("The value of b before swap is $b")
// Swapping of two numbers
// using exclusive OR operation (i.e. XOR)
a = a.xor(b)
b = a.xor(b)
a = a.xor(b)
println("The value of a after swap is $a")
println("The value of b after swap is $b")
}
Output
The value of a before swap is 3
The value of b before swap is 6
The value of a after swap is 6
The value of b after swap is 3