Efficient swapping of elements of an array in Java

JavaAlgorithmSwap

Java Problem Overview


I am wondering if there is a more efficient way of swapping two elements in an Array, than doing something like this:

String temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;

Well, this is obviously not bad or even wrong, but I need to swap very often so I am interested if there are any Libs or something that provide a more efficient way to do this?

Java Solutions


Solution 1 - Java

Nope. You could have a function to make it more concise each place you use it, but in the end, the work done would be the same (plus the overhead of the function call, until/unless HotSpot moved it inline — to help it with that, make the function static final).

Solution 2 - Java

This should make it seamless:

public static final <T> void swap (T[] a, int i, int j) {
  T t = a[i];
  a[i] = a[j];
  a[j] = t;
}

public static final <T> void swap (List<T> l, int i, int j) {
  Collections.<T>swap(l, i, j);
}

private void test() {
  String [] a = {"Hello", "Goodbye"};
  swap(a, 0, 1);
  System.out.println("a:"+Arrays.toString(a));
  List<String> l = new ArrayList<String>(Arrays.asList(a));
  swap(l, 0, 1);
  System.out.println("l:"+l);
}

Solution 3 - Java

If you're swapping numbers and want a concise way to write the code without creating a separate function or using a confusing XOR hack, I find this is much easier to understand and it's also a one liner.

public static void swap(int[] arr, int i, int j) {
	arr[i] = (arr[i] + arr[j]) - (arr[j] = arr[i]);
}

What I've seen from some primitive benchmarks is that the performance difference is basically negligible as well.

This is one of the standard ways for swapping array elements without using a temporary variable, at least for integers.

Solution 4 - Java

If you want to swap string. it's already the efficient way to do that.

However, if you want to swap integer, you can use XOR to swap two integers more efficiently like this:

int a = 1; int b = 2; a ^= b; b ^= a; a ^= b;

Solution 5 - Java

Use Collections.swap and Arrays.asList:

Collections.swap(Arrays.asList(arr), i, j);

Solution 6 - Java

inplace swapping (incase you already didn't know) can save a bit of space by not creating a temp variable.

arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];

Solution 7 - Java

Incredibly late to the party (my apologies) but a more generic solution than those provided here can be implemented (will work with primitives and non-primitives alike):

public static void swap(final Object array, final int i, final int j) {
    final Object atI = Array.get(array, i);
    Array.set(array, i, Array.get(array, j));
    Array.set(array, j, atI);
}

You lose compile-time safety, but it should do the trick.

Note I: You'll get a NullPointerException if the given array is null, an IllegalArgumentException if the given array is not an array, and an ArrayIndexOutOfBoundsException if either of the indices aren't valid for the given array.

Note II: Having separate methods for this for every array type (Object[] and all primitive types) would be more performant (using the other approaches given here) since this requires some boxing/unboxing. But it'd also be a whole lot more code to write/maintain.

Solution 8 - Java

Try this:

	int lowIndex = 0;
	int highIndex = elements.length-1;
	
	while(lowIndex < highIndex) {
		T lowVal = elements[lowIndex];
		T highVal = elements[highIndex];
		elements[lowIndex] = highVal;
		elements[highIndex] = lowVal;
		
		lowIndex += 1;
		highIndex -=1;
	}

Solution 9 - Java

first of all you shouldn't write for (int k = 0; k **<** data.length **- 1**; k++) because the < is until the k is smaller the length -1 and then the loop will run until the last position in the array and won't get the last place in the array; so you can fix it by two ways: 1: for (int k = 0; k <= data.length - 1; k++) 2: for (int k = 0; k < data.length; k++) and then it will work fine!!! and to swap you can use: to keep one of the int's in another place and then to replace

int x = data[k]
data[k] = data[data.length - 1]
data[data.length - 1] = x;

because you don't want to lose one of the int's!!

Solution 10 - Java

Solution for object and primitive types:

public static final <T> void swap(final T[] arr, final int i, final int j) {
    T tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final boolean[] arr, final int i, final int j) {
    boolean tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final byte[] arr, final int i, final int j) {
    byte tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final short[] arr, final int i, final int j) {
    short tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final int[] arr, final int i, final int j) {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final long[] arr, final int i, final int j) {
    long tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final char[] arr, final int i, final int j) {
    char tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final float[] arr, final int i, final int j) {
    float tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final double[] arr, final int i, final int j) {
    double tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

Solution 11 - Java

This is just "hack" style method:

int d[][] = new int[n][n];

static int swap(int a, int b) {
  return a;
}
...

in main class --> 

d[i][j + 1] = swap(d[i][j], d[i][j] = d[i][j + 1])

Solution 12 - Java

public static final void swap (int[] a, int i, int j) {
    a[i] = a[i] + a[j];
    a[j] = a[i] - a[j];
    a[i] = a[i] - a[j];
}

Solution 13 - Java

public class SwapElements {

public static void main(String[] args) {

	int[] arr1 = new int[5];
	int[] arr2 = {10,20,30,40};
	
	System.out.println("arr1 Before Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 Before Swapping " + Arrays.toString(arr2));
	
	int temp[];
	arr1[3] = 5;
	arr1[0] = 2;
	arr1[1] = 3;
	arr1[2] = 6;
	arr1[4] = 10;

	temp = arr1;
	arr1 = arr2;
	arr2 = temp;
	System.out.println("arr1 after Swapping " + Arrays.toString(arr1));
	System.out.println("arr2 after Swapping " + Arrays.toString(arr2));
}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobinView Question on Stackoverflow
Solution 1 - JavaT.J. CrowderView Answer on Stackoverflow
Solution 2 - JavaOldCurmudgeonView Answer on Stackoverflow
Solution 3 - JavakmecppView Answer on Stackoverflow
Solution 4 - Javabhuang3View Answer on Stackoverflow
Solution 5 - JavaZhekaKozlovView Answer on Stackoverflow
Solution 6 - JavaNeel AlexView Answer on Stackoverflow
Solution 7 - JavaBeUndeadView Answer on Stackoverflow
Solution 8 - JavaJ.user94View Answer on Stackoverflow
Solution 9 - Javaviper-zeroView Answer on Stackoverflow
Solution 10 - JavaError404View Answer on Stackoverflow
Solution 11 - JavababnogView Answer on Stackoverflow
Solution 12 - JavaAnilView Answer on Stackoverflow
Solution 13 - JavaAnu SathiyaView Answer on Stackoverflow