-1

I am trying to write a swap method in the form of

swap(T[], int, int)

This method should take an array and swap two of the positions in that array. For example, say I have an array named table and two arbitrary integers in that array called up and down. I would like to be able to use the method swap so that:

swap(table, up, down);

will swap the values at the position of up and down in the given array of table. Could anyone help me out? I know I need to use a temp to store the values but I'm not quite sure what I need to do beyond that.

Teej
  • 229
  • 2
  • 4
  • 12

1 Answers1

-1
static <T> void swap(T[] array, int a, int b){
    T temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}
Keiwan
  • 8,031
  • 5
  • 36
  • 49
  • Would it be possible for the method to be able to take integer values of different variable names? For example, calling swap(table, up, down) and swap(table, first, last) with swap still being the same function just different variable names inputted for integers? If that makes sense – Teej Apr 26 '16 at 15:24
  • Yes, that's possible. I can make the parameter names more general if that makes it clearer for you. – Keiwan Apr 26 '16 at 15:27