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;
}