0

How do I swap two array values given an array of integers and two integer values?

The code I used is

public class Q1K {
    void swapElements(int[] array, int index1, int index2){
        int index3= array[index1];
        array[index1]=array[index2];
        array[index2]= array[index3];
    }
}

Sorry if my question is missing info/hard to understand

Kieran
  • 43
  • 3

6 Answers6

3

You already figured out that you'll need a temporary variable to perform a basic swap in Java. But the naming of the variable (index3 in your case) suggests that you mix things up; the goal is not to temporarily store an index of your array, but the value that is represented by that index - otherwise, it would be overwritten (and thus lost). What you want to do in "step 3" of the swap is to restore the temporary value itself, not the value behind an index.

So:

void swapElements(int[] array, int index1, int index2){
        int tempValue = array[index1];
        array[index1] = array[index2];
        array[index2] = tempValue;
}
fxfour
  • 143
  • 1
  • 10
2

It should be,

int temp = array[index1]; // its not a index, its a value at a particular index.
array[index1]=array[index2];
array[index2]= temp;

The naming convention you used is quiet confusing index3, it actually should be a temporary variable used for swapping.

BatScream
  • 19,260
  • 4
  • 52
  • 68
2

array[index3]; will return the value from the array again . so you need to write it as index3 instead.

Name your variables wisely to avoid confusion, Also remember [] values inside the braces denotes the position always.

Learn More on swapping arrays.

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56
1

Your answer is very close. Take a look at this solution...

public class Q1K {
    void swapElements(int[] array, int index1, int index2){
        int val = array[index1];
        array[index1] = array[index2];
        array[index2] = val;
    }
}
xagyg
  • 9,562
  • 2
  • 32
  • 29
1
public class Q1K {
    void swapElements(int[] array, int index1, int index2){
        int index3= array[index1];
        array[index1]=array[index2];
        array[index2]= index3;
    }
}

Make sure you name your variables such that they make sense when reading the code. From your code, index3 sounds like an index of array but in the code context it really is not :)

WAQ
  • 2,556
  • 6
  • 45
  • 86
0

There is another way that don't need to use temporary variable:

void swapElements(int[] array, int ix1, int ix2){
    array[ix1] = array[ix1] + array[ix2];
    array[ix2] = array[ix1] - array[ix2];
    array[ix1] = array[ix1] - array[ix2];
}
przemek hertel
  • 3,924
  • 1
  • 19
  • 27