0

Please help me to understand what is going on here:

Main.java:

int[] myarray = new int[125];
// setup the array here, code omitted. 

int minimum = ProcessArray.min(myarray );


// the array values will now print as if they have been sorted...
for(int I=0; I<myarray.length;i++) {
   System.out.Println(myarray[i]);
}

ProcessArray.java

import java.util.Arrays;

public class ProcessArray {
  public static int min(int[] anarray){
     Arrays.sort(anarray);
     return anarray[0];
  }


}

after finding the minimum value of the array, the array will print in sorted order.

Why does the array get re-arranged in sorted order?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Scott.Thornton
  • 102
  • 1
  • 8

2 Answers2

1

when you pass an array into a function it is a reference to myarray not a clone/copy

your minimum function sorted the array, so it is sorted after the call

you can clone the array manually that would keep the original array

int minimum = ProcessArray.min(myarray.clone()); or use Arrays.copyOf(..)

keep in mind that the clone/copy is a "shallow copy" if it was an array of some objects the objects would still be the same...

take a look at this question Is Java "pass-by-reference" or "pass-by-value"?

Community
  • 1
  • 1
Derte Trdelnik
  • 2,656
  • 1
  • 22
  • 26
  • Hi Derte, thanks for your answer\comment. Particulary referencing the terminology I had long forgotten about ( pass by ref, pass by value). – Scott.Thornton Aug 08 '16 at 07:59
  • I was thinking it might have had to do with the fact that the class ProcessArray was not instantiated. Am helping my partner with an assignment, and the advice that she was given was that they were not required to instantiate the class. I thought it might have been bad advice – Scott.Thornton Aug 08 '16 at 08:05
  • no, it does not matter whether you instantiate the class, the array would still be passed as reference, in this case having a static function makes more sense as the min function does not use or alter the state of the class it is defined in – Derte Trdelnik Aug 08 '16 at 08:34
1

As per javadoc Arrays.sort method will sort the elements in an array in ascending order.

If you expect that your array should not rearrange and also you need to find min and max in your array you can use like below,

Integer[] a = {3,5,1,2,4};

for (int i = 0; i < a.length; i++)
{
    System.out.println(a[i]);
}

System.out.println("max :"+Collections.max(Arrays.asList(a)));
System.out.println("min :"+Collections.min(Arrays.asList(a)));

System.out.println("after find min and max array :"+ Arrays.asList(a));

By use collections that wont rearrange your array.

Bhuvanesh Waran
  • 593
  • 12
  • 28