my bubble sort code is only swapping the 1st array item. All other items are left as 0. I think my nested loops are wrong or something I haven’t been able to diagnose it correctly yet. so here is my code.
public void swap(int i, int j) {
int temp;
temp = i;
i = j;
j = temp;
}
public void sortArray(int [] sourceArray, int [] targetArray, int allArraySize){
for(int i = 0; i < allArraySize; i++) {
targetArray[i] = sourceArray[i];
for (i = 0; i < allArraySize; i++) {
for(int j = i+1; j < allArraySize;j++) {
if(targetArray[i] > targetArray[j]) {
swap(i, j);
}
}
}
}
}
thanks so much for the feedback. I am (obviously) new to programming. I have changed my code to this.
public void sortArray(int [] sourceArray, int [] targetArray, int allArraySize){
int temp;
for(int i = 0; i < allArraySize; i++) {
targetArray[i] = sourceArray[i];
for (i = 0; i < allArraySize; i++) {
for(int j = i+1; j < allArraySize;j++) {
if(targetArray[i] > targetArray[j]) {
temp = targetArray[i];
targetArray[i] = targetArray[j];
targetArray[j] = temp;
}
}
}
}
}
and the result is still only swapping 1 item but now it is the last 1. if anyone is still able to help I would greatly appreciate it.
The reason is explained in detail in this post. In summary, java passes arguments by value and your
swapmethod only swaps local variables but has no effect on the variables in yoursortArraymethod.An easy fix would be to include the code of
swapdirectly in yourif. Note: I have not checked the rest of your code. For example, you probably meant to swap the elements in the array rather than the indexes.