Swap Values

While programming in most (never say all) programming languages and platforms one often runs into the need to swap the values of two variables. The following code in Java illustrates a first attempt to swap two integers:

	/*
	 * Swap two integers.
	 */
	public static void swap(int a, int b) {
		int temp = a;
		a = b;
		b = temp;
		System.out.println("swap <<< a: " + a + " b: " + b);
	}

The logic seems to be fine. Store the first value into a temporary variable for later use. Replace the value of ‘a’ with the value of ‘b’. Set ‘b’ with the original value of ‘a’ (not stored in ‘temp’). To make sure our logic is correct we display the values just before we leave the method.

The following test code is used to verify the swap() method:

	/*
	 * Test code.
	 */
	public static void main(String[] args) {

		// **** ****
		
		Scanner sc = new Scanner(System.in);
		
		// **** ****
		
		System.out.print("main <<< a: ");
		int a = sc.nextInt();
		
		System.out.print("main <<< b: ");
		int b = sc.nextInt();

		// ***** display initial values ****
		
		System.out.println("main <<< a: " + a + " b: " + b);
		
		// ***** close scanner ****
		
		sc.close();
		
		// **** swap the integers ****
		
		swap(a, b);
		
		// **** display swapped values ****
		
		System.out.println("main <<< a: " + a + " b: " + b + "\n");		
	}

In the test we prompt for the values of two integers. We display them to make sure all is well. We then invoke the method which displays the values just before the method returns. Just to make sure all is well we displayed the swapped value in the main program. Following is a screen capture of the console using the Eclipse Neon.3 IDE:

main <<< a: 2
main <<< b: 3
main <<< a: 2 b: 3
swap <<< a: 3 b: 2
main <<< a: 2 b: 3

All went well until we displayed the swapped values in our main program. The reason for this is that the variables ‘a’ and ‘b’ were passed by value to the swap() method.

What this means is that the swap() method receives the values of the variables in the main program. The swap() method operates correctly but when the method returns, the contents of the variables are not swapped. We need to somehow pass the variables by reference.  This means that the addresses of ‘a’ and ‘b’ need to be passed so the swap() method operates on the original memory locations in the main() program and not on copies.

Let’s take a look at the following Java code:

import java.util.Scanner;

public class Solution {
	
	/*
	 * Swap two Integers.
	 */
	public static void Swap(Integer aa, Integer bb) {
		Integer temp = aa;
		aa = bb;
		bb = temp;
		System.out.println("Swap <<< aa: " + aa + " bb: " + bb);
	}
	
	/*
	 * Swap two integers.
	 */
	public static void swap(int a, int b) {
		int temp = a;
		a = b;
		b = temp;
		System.out.println("swap <<< a: " + a + " b: " + b);
	}

	/*
	 * Test code.
	 */
	public static void main(String[] args) {

		// **** ****
		
		Scanner sc = new Scanner(System.in);
		
		// **** ****
		
		System.out.print("main <<< a: ");
		int a = sc.nextInt();
		
		System.out.print("main <<< b: ");
		int b = sc.nextInt();

		// ***** display initial values ****
		
		System.out.println("main <<< a: " + a + " b: " + b);
		
		// ***** close scanner ****
		
		sc.close();
		
		// **** swap the integers ****
		
		swap(a, b);
		
		// **** display swapped values ****
		
		System.out.println("main <<< a: " + a + " b: " + b + "\n");
		
		// **** ****
		
		Integer aa = a;
		Integer bb = b;
		System.out.println("main <<< aa: " + aa + " bb: " + bb);
	
		// **** ****
		
		Swap(aa, bb);
		
		// **** display swapped values ****
		
		System.out.println("main <<< aa: " + aa + " bb: " + bb + "\n");
	}
}

Following is a screen capture of the console from the IDE:

main <<< a: 2
main <<< b: 3
main <<< a: 2 b: 3
swap <<< a: 3 b: 2
main <<< a: 2 b: 3

main <<< aa: 2 bb: 3
Swap <<< aa: 3 bb: 2
main <<< aa: 2 bb: 3

It seems that objects are also passed by value and not by reference. Let’s try one more approach by passing the values to be swapped as elements in an array. Following is the output from the console:

main <<< a: 2
main <<< b: 3
main <<< a: 2 b: 3
swap <<< a: 3 b: 2
main <<< a: 2 b: 3

main <<< aa: 2 bb: 3
Swap <<< aa: 3 bb: 2
main <<< aa: 2 bb: 3

main <<< arr[0]: 2 arr[1]: 3
SwapArray <<< arr[0]: 3 arr[1]: 2
main <<< arr[0]: 3 arr[1]: 2

It seems that the last update worked. Let’s now take a look at the Java code:

import java.util.Scanner;

public class Solution {
	
	/*
	 * Swap to entries in the array.
	 */
	static void SwapArray(int[] arr) {
		int length = arr.length;
		if (length < 2) {
			System.out.println("SwapArray <<< UNEXPECTED length: " + length);
			return;
		}
		int temp = arr[0];
		arr[0] = arr[1];
		arr[1] = temp;
		System.out.println("SwapArray <<< arr[0]: " + arr[0] + " arr[1]: " + arr[1]);
	}
	
	/*
	 * Swap two Integers.
	 */
	public static void Swap(Integer aa, Integer bb) {
		Integer temp = aa;
		aa = bb;
		bb = temp;
		System.out.println("Swap <<< aa: " + aa + " bb: " + bb);
	}
	
	/*
	 * Swap two integers.
	 */
	public static void swap(int a, int b) {
		int temp = a;
		a = b;
		b = temp;
		System.out.println("swap <<< a: " + a + " b: " + b);
	}

	/*
	 * Test code.
	 */
	public static void main(String[] args) {

		// **** ****
		
		Scanner sc = new Scanner(System.in);
		
		// **** ****
		
		System.out.print("main <<< a: ");
		int a = sc.nextInt();
		
		System.out.print("main <<< b: ");
		int b = sc.nextInt();

		// ***** display initial values ****
		
		System.out.println("main <<< a: " + a + " b: " + b);
		
		// ***** close scanner ****
		
		sc.close();
		
		// **** swap the integers ****
		
		swap(a, b);
		
		// **** display swapped values ****
		
		System.out.println("main <<< a: " + a + " b: " + b + "\n");
		
		// **** ****
		
		Integer aa = a;
		Integer bb = b;
		System.out.println("main <<< aa: " + aa + " bb: " + bb);
	
		// **** ****
		
		Swap(aa, bb);
		
		// **** display swapped values ****
		
		System.out.println("main <<< aa: " + aa + " bb: " + bb + "\n");
	
		// **** ****
		
		int[] arr = new int[2];
		arr[0] = a;
		arr[1] = b;
		System.out.println("main <<< arr[0]: " + arr[0] + " arr[1]: " + arr[1]);
		
		// **** swap the first two entries in the specified array ****
		
		SwapArray(arr);
		
		// **** display swapped values ****
		
		System.out.println("main <<< arr[0]: " + arr[0] + " arr[1]: " + arr[1]);		
	}

}

Instead of passing each integer we used an array of integers. The first two entries were swapped. All worked in the method and in the main procedure. Keep in mind that in Java arguments are passed by value and not by reference.

If we decide to use a different programming language i.e., C or C++ the initial code could look as follows using the Microsoft Visual Studio Enterprise Edition IDE:

#include <iostream>

using namespace std;

/*
*/
static void swap(int a, int b) {
	int temp = a;
	a = b;
	b = temp;
	cout << "swap <<< a: " << a << " b: " << b << endl;
}

/*
Test code.
*/
int main() {

	// **** ****

	int a, b = 0;

	// **** ****

	cout << "main <<< a: "; cin >> a;
	cout << "main <<< b: "; cin >> b;
	cout << "main <<< a: " << a << " b: " << b << endl;

	// **** swap by value ****

	swap(a, b);

	// **** display swapped values ****

	cout << "main <<< a: " << a << " b: " << b << endl << endl;

	// **** ****

	return 0;
}

The output on a console would look like:

main <<< a: 2
main <<< b: 3
main <<< a: 2 b: 3
swap <<< a: 3 b: 2
main <<< a: 2 b: 3

It worked inside the swap() method but did not changed the variables in the main() due to the fact that the variables were passed by value.

At this time we could just change the method or just create a new method in which the variables are passed by reference as illustrated by the following C++ code:


#include <iostream>

using namespace std;

/*
*/
static void Swap(int *a, int *b) {
	int temp = *a;
	*a = *b;
	*b = temp;
	cout << "Swap <<< *a: " << *a << " *b: " << *b << endl;
}

/*
*/
static void swap(int a, int b) {
	int temp = a;
	a = b;
	b = temp;
	cout << "swap <<< a: " << a << " b: " << b << endl;
}

/*
Test code.
*/
int main() {

	// **** ****

	int a, b = 0;

	// **** ****

	cout << "main <<< a: "; cin >> a;
	cout << "main <<< b: "; cin >> b;
	cout << "main <<< a: " << a << " b: " << b << endl;

	// **** swap by value ****

	swap(a, b);

	// **** display swapped values ****

	cout << "main <<< a: " << a << " b: " << b << endl << endl;

	// **** swap by reference ****

	Swap(&a, &b);

	// **** display swapped values ****

	cout << "main <<< a: " << a << " b: " << b << endl;

	// **** ****

	return 0;
}

Now when we run the code:

main <<< a: 2
main <<< b: 3
main <<< a: 2 b: 3
swap <<< a: 3 b: 2
main <<< a: 2 b: 3

Swap <<< *a: 3 *b: 2
main <<< a: 3 b: 2

We can verify that it worked inside the Swap() method and also in the main() program. The reason being that we passed the address of the variables to the Swap() method.

If you have comments / questions regarding this or any other post in this blog, please leave me a comment. I will address it as soon as possible.

Enjoy;

John

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *