Here is a quick explanation of how the swapping works.
public static void swapByIndex(int myArray[], int index1, int index2) {
int position1 = myArray[index1];
int position2 = myArray[index2];
// At this point, you already know both the indexes and the values.
// You can just assign the values directly.
myArray[index1] = position2;
myArray[index2] = position1;
}
Now, once you have this, you might notice that we only need to store one of the values in a temporary variable. We can reduce it further to the far more common form:
public static void swapByIndex(int myArray[], int index1, int index2) {
int position1 = myArray[index1];
// Overwrite the value stored at index 1
myArray[index1] = myArray[index2];
// Use the stored value to then fill in the second index
myArray[index2] = position1;
}
This is how we can arrive at the most common version of the swapping function.
public static void swap(int[] array, int a, int b) {
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
While I don't recommend it if you are just starting to learn java, you can also use the generic version that will work for any type of array.
public static <T> void swap(T[] array, int a, int b) {
T tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}