Swap

In order to switch two values in an array we use a technique called swapping.

Swap method

public static void swap(int[] x, int i, int j) {
   int temp = x[i];
   x[i] = x[j];
   x[j] = temp;
}

In the case above, the value which was in the index x[j] is switched with the value which was in x[i]

Visual Swap Method

swap.JPG

Necessity of Temporary Variable

If you do not write the code using a temporary variable overwriting will occur.
Example of incorrect swapping:

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

In this case, x[i] is already replaced with x[j] before the statement x[j] = x[i] so once the program ends, x[i] and x[j] are now equal to what x[j] was previously.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License