JT Thompson
JT Thompson

Reputation: 19

Swapping multi-dimensional array elements

I have a multi-dimensional array and I have a typical swap function but would the function apply to any number of dimensions? For example,

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

This works for a regular array. But I need to swap two indices of a 2D array. Could I use the same function but just call the parameters differently?

Sample Input:

int[][] arr = {{1}, {2}, {3}};
System.out.println(arr[0][0]);

// I am confused on
// what these parameters should be
swap(arr, arr[0][0], arr[1][0]);

System.out.println(arr[0][0]);

Sample Output:

1
2

Upvotes: 1

Views: 355

Answers (2)

Marwen Jaffel
Marwen Jaffel

Reputation: 822

You can use this function with 4 params :

public static void swap(int [][]t,int a, int b,int c,int d) {
    int temp = t[a][b];
    t[a][b] = t[c][d];
    t[c][d] = temp;
}

Upvotes: 0

Yes, it is possible, I recommend to send arr as method parameter:

public static <T> void swap(T[] arr, int a, int b) {
    T temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
}
public static void main(String[] args) {
    int[][] a = {{1,2},{3,4}};
    swap(a,0,1);
    System.out.println(Arrays.deepToString(a));
}

In your case, T resolves to one-dimensional array int[].

Upvotes: 1

Related Questions