1

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

2 Answers 2

1

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[].

Sign up to request clarification or add additional context in comments.

3 Comments

@JTThompson Note that mine and Marwen's solutions solve different problems since your sentence But I need to swap two indices of a 2D array. can be interpreted in either way. Please give sample input and expected output for the next time in order to avoid ambiguity.
Nope. Make clear the part with comment where you state you are confused. I believe it helps you to find what you actually want to achieve. Use more elements in example, think out how the ideal invocation of swap function should look like and dump whole array to sysout.
I will do that thanks! A very good point. I will try to show more clearly what I want next time. Once again, thanks very much!
0

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;
}

1 Comment

Thank you for this! Sorry my question was ambiguous, this is however the answer that I was seeking. Works well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.