0

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 ?

VLDCNDN
  • 692
  • 1
  • 7
  • 19

3 Answers3

1

When you make the assignment int[] value = arr, you give value the same reference as arr. This means that assigning, for example, value[1] will affect the original array. If you want to return a new sorted array without affecting the original one, then you can try making a copy of it:

public int[] Sort(int[] arr) {
    int[] value = new int[arr.length];
    System.arraycopy(arr, 0, value, 0, arr.length);

    // ...
    return value;
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Here is another approach, You'd clone the array and sort

int[] value = arr.clone();

any operation on the cloned array wont affect the original array.

Ex

    int[] arr = { 1, 4, 3 };
    int[] a = arr.clone();
    a[2] = 5;
    System.out.println(Arrays.toString(arr));
    System.out.println(Arrays.toString(a));

output

[1, 4, 3]
[1, 4, 5]
Saravana
  • 12,647
  • 2
  • 39
  • 57
0

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154