Issue
I am implementing bubble sort in java when I write the code this way no sort happens.
public int [] sort(int [] array) {
for(int counter1 = 0; counter1 < array.length; counter1 ++) {
for(int counter2 = counter1; counter2 < array.length; counter2 ++) {
if(array[counter1] > array[counter2]) service.swap(array[counter1], array[counter2]);
}
}
return array;
}
this is the swap method
public class service {
public static void swap(int value1, int value2) {
value1 = value1 ^ value2;
value2 = value1 ^ value2;
value1 = value1 ^ value2;
}
}
but when I write it this way it works
public int [] sort(int [] array) {
for(int counter1 = 0; counter1 < array.length; counter1 ++) {
for(int counter2 = counter1; counter2 < array.length; counter2 ++) {
if(array[counter1] > array[counter2]) {
array[counter1] = array[counter1] ^ array[counter2];
array[counter2] = array[counter1] ^ array[counter2];
array[counter1] = array[counter1] ^ array[counter2];
}
}
}
return array;
}
I know that after the method ends the memory for it in stack is deleted, at least that is what I know from c language. In c I used to use pointers, but there is no pointers in java. is there a way to implement swap inside a method and keep the updated change?
Solution
The function arguments are only in the local scope of the function. This means that
value1 = value1 ^ value2;
only effects the variable value1 that is local to the function call. This is because int is a primitive type in Java, meaning that a variable of its type stores only its value.
It is different with non-primitive types, where a variable stores a reference (sort of like a pointer) to the object. A function call with non-primitive types (such as Integer) would mean that the actual objects behind the reference are changed, which would allow an external function like yours. Nonetheless, in this use case you should prefer using primitives and swapping in place.
Maybe this will help explaining non-primitive types: https://www.baeldung.com/java-pass-by-value-or-pass-by-reference
Answered By - chris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.