Roy Mustang Roy Mustang - 5 months ago 9
Java Question

Passing an Array and sort

Good day guys, I am trying to sort here using an array, Check my codes

public int[] Sort(int[] arr) {
int[] value = arr;
int min, temp, out;


for (out = 0; out < value.length - 1; out++) {
for (min = out + 1; min < value.length; min++) {
if(value[out] > value[min]){
temp = value[min];
value[min] = value[out];
value[out] = temp;
}
}
}
return value;
}


The problem here is I pass the array 'arr' value to the array 'value' and sort the 'value' array then the output is what i expect, he sorted the number, but the problem is, when i tried to return the 'arr' array it also return a sorted value even though i didn't tried to sort it .. is it a bug or just my ugly coding ?

Answer

Your variables arr and value both point to the same array.

Apparently you thought your sorting manipulations were applied to a second array. But, no, you were changing the original array.

Learn about reference variables. The two variables are not an array themselves, they are a pointer to an array that lives elsewhere in memory. So there are three “things” in play here. One reference variable, another reference variable, and an array. All three are distinct from one another.

When these reference variables go out of scope or get assigned to another object, so no more reference variables point to the array object, then the array object becomes a candidate for garbage collection.

Seems that you want to copy the array to another array. Stack Overflow has many Questions and Answers on the topic of copying an array in Java for you to study. Like this one.

Comments