0

I'm a programming beginner and I have question regarding a return value from a function.

I´m studying Java.

I have attached code from my book that features a classic Selection Sort.

Now obviously the code from the book works. However, these three lines in main function are the basis of my question:

  1. int []a=new int[]{1,9,2,8,3,7,4,6,5};

  2. sort(a);

  3. if(ascending(a)) System.out.println("Works");

So my question is:

In line 2, how can I retrieve a sorted a[] if sort() function is void?

And shouldn´t the line be: a = sort(a)?

public class SelectionSort
{

    public static void main(String[]args)
    {
        int []a=new int[]{1,9,2,8,3,7,4,6,5};
        sort(a);
        if(ascending(a)) System.out.println("Virðist virka");
        else System.out.println("Virkarekki");
    }

    public static void sort(int[]a)
    {
        if(a.length<2) return;
        int i=0;
        while(i!=a.length)
        {
            int k=i+1;
            while(k!=a.length)
            {
                if(a[k]<a[i])
                {
                    int tmp=a[i];
                    a[i]=a[k];
                    a[k]=tmp;
                }
            k++;
            }
        i++;
        }
    }

    public static boolean ascending(int[]a)
    {
        if(a.length<2) return true;
        int i=1;
        while(i!=a.length)
        {
            if(a[i-1]>a[i]) return false;
            i++;
        }
        return true;
    }
}
  • 3
    The `sort` method modifies the array you pass, so you don't need to have a return type. – August Oct 16 '14 at 00:48
  • As @August indicated, the `sort` method changes the original array. It has to do with how Java handles parameters: http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Alex Oct 16 '14 at 00:54

5 Answers5

2

Since arrays are objects, they are passed by their reference (their location in memory), so the changes within sort() to a[] also change a[] declared in main. So a is changed within the function. However, you cannot say

public static void change(int[] a) {
    a = new int[3];
    a = {1, 2};
}

That will not change a itself, because that just makes a new memory location that the parameter a points to, without changing the parameter.

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48
0

The sort() method modifies the array passed as an argument; that is, the original array is modified.

Say you have array a which value is [ 3, 2 ]; you call sort(a); if your code looks like:

// printArray is an hypothetical method
printArray(a);
sort(a);
printArray(a);

then the output would be:

[3, 2]
[2, 3]

As a result there is no need for sort() to return a result at all.

You can however modify the sort() method to make a copy of the array, sort the copy and return that copy.

fge
  • 119,121
  • 33
  • 254
  • 329
0

sort(int[] a), a void function, does not return a value.

Instead, sort() modifies the array passed to it in-place. You passed an array object to sort() and your code modified it.

joshreesjones
  • 1,934
  • 5
  • 24
  • 42
0

http://javadude.com/articles/passbyvalue.htm

primitives in java such as char and int are passed by value in java.

an array in java is simply a object container for whatever the type is..

in java passing objects as parameters is similar to passing as a reference - where any modifications you make to the object passed in through the parameter will retain those changes in the calling method.

0

You are touching upon a concept in programming languages named pass by reference vs pass by value.

When you "pass an object by value" to a method, a copy of that object is taken and that copy is passed to the method. So in the called method, when you modify the object, the modification does not get reflected in the caller method.

When you "pass an object by reference" to a method, only a pointer to the actual object that it is referring to is passed to the method. So in the called method, when you modify the object, the modification does get reflected in the caller method.

In Java, all method arguments are "passed by value". It is easier to think that it is pass by reference but it is not the case.

Now, all object variables are references in Java. So in this case, the array is a reference. Java passes that array reference by value i.e it takes a copy of the "reference" and passes it.

So you can now imagine two pointers to the same array - original one named "args" in main() and the new one named "a" in sort()

Since the underlying array is the same, it does not matter if you modify the array using the pointer "args" in the main() or the pointer "a" sort(). They both will see the change.

It is also the reason - why a swap will not work as you would expect.

void main()
{
   badSwap(arr1, arr2); 
   // arr1 and arr2 will still point to same values as the prior line
   // because only the reference pointers are getting swapped
   // however, arr1[0] will be -99
}

void badSwap(int[] a, int[] b)
{
   a[0] = -99;
   int[] temp = a;
   a = b;
   b = temp; 
}
govin
  • 6,445
  • 5
  • 43
  • 56