0

I want to use sorting for array of number, here the code:

package SortAlgorithm;

public abstract class Sort {
    abstract int[] sort(int[] array);

    void swap(int a,int b){
        int temp;
        temp = a;
        a = b;
        b = temp;
    }

    static void print(int[] array){
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i]+" ");
        }
    }
}

public class SelectionSort extends Sort{

    private int indexMin = 0;

    public int[] sort(int[] arrNum){
        int[] numbers = arrNum;

        for(int i = 0; i < numbers.length; i++){
            indexMin = i;
            for(int j = i + 1; j < numbers.length; j++){
                if(numbers[j] < numbers[indexMin]){
                    indexMin = j;
                }
            }
            int temp = numbers[i];
            numbers[i] = numbers[indexMin];
            numbers[indexMin] = temp;
        }

        return numbers;
    }
}

public class MSorting {

    static int[] hasilSort;

    public static void main (String[] args){
        int[] arrNum = {4,7,5,9,1};
        Sort.print(arrNum);
        System.out.println();

        SelectionSort sortSatu = new SelectionSort();
        hasilSort = sortSatu.sort(arrNum);
        Sort.print(hasilSort);
        System.out.println();
        Sort.print(arrNum);
    }
}

When I run the code, the output is weird. This is the output I get:

4 7 5 9 1
1 4 5 7 9 
1 4 5 7 9 

But I want the output like this:

4 7 5 9 1 
1 4 5 7 9 
4 7 5 9 1 

What's wrong??

1 Answer 1

1

by doing int[] numbers = arrNum; in your sort method you are assigning the reference of arrNum to numbers, which by swaping the values for the array numbers essentially let´s you swap the values for arrNum aswell. That´s logical, because they refer to the same int array instance.

you should copy the value into numbers if you don´t want to change the original array. this can be done by simply looping over arrNum and assigning each value to numbers for each respective position like this:

int[] numbers = new int[arrNum.length];
for(int i = 0;i<arrNum.length;++i) {
    numbers[i] = arrNum[i];
}

or you use the implementation to copy arrays provided by the system class.

int[] numbers = new int[arrNum.length];
System.arraycopy(arrNum, 0, numbers, 0, arrNum.length);
Sign up to request clarification or add additional context in comments.

2 Comments

but, when i change the swap process in Selection Sort with swap that inherits from class Sort, it can't swap,, why??
@diaz because java is pass-by-value. The one with the array did only work due to it beeing an array, and arrays are treated as objects. But when you reassign an int nothing will change for the variables passed by the caller

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.