I am trying to code some pseudocode that was given on an assignment – however the coding portion I’m doing now is not part of the assignment and is just for fun.
One part of the pseudocode says “swap elements of the array”. In my code I have to do this in two places. However I was wondering if there’s a way to do this by creating only one method, i.e. creating another method that simply swaps them and saves the extra lines of code I used each time I wanted to run it.
The problem is, if I create a brand new method outside of this one, I’ll have to send in the array as a parameter and take it out as well, and I’m afraid this will be less efficient (obviously no big deal here but I’m trying to learn for future larger projects).
Here is my code containing the repeated “swap” method lines.
public int[] myAlgorithm(int[] arrayOfInts, int size){
boolean done = true;
int j= 0;
while (j <= n-2){
if (arrayOfInts[j] > arrayOfInts[j+1]){
int tempHolder = arrayOfInts[j];
arrayOfInts[j] = arrayOfInts[j+1];
arrayOfInts[j+1] = tempHolder;
done = false;
}
j = j + 1;
}
j = size - 1;
while (j >= 1){
if (arrayOfInts[j] <= arrayOfInts[j-1]){
int tempHolder = arrayOfInts[j];
arrayOfInts[j] = arrayOfInts[j+1];
arrayOfInts[j+1] = tempHolder;
done = false;
}
j--;
}
if (!done)
myAlgorithm(arrayOfInts, size)
else
return arrayOfInts;
}
You only need to “send it” and work on the array directly. In practice, passing a parameter to a method is a very cheap operation which, if called often enough, will likely be optimised by the compiler anyway so you should not worry about it too much (unless you prove that it is a performance penalty by profiling your application).
In your case, you could have a method such as:
and you would call it:
Why does it work?
Java passes arguments by value, but in the case of objects (i.e. non-primitive types, including arrays), the value that is passed is the reference to the object. In other words, the argument to the swap method is a reference to the same array as in the calling code, so you can work on that array directly, without having to send it back to the calling method.