0

I'm trying to make a project in which an array is sorted by different sorting algorithms. However, I have noticed that after one algorithm sorts the array and displays the value, the original array is also changed. How can I solve this?

public static void main(String[] args) {
   
    int[] array = {20, 35, -15, 7, 55, 1, -2};
    
    printArray(array);       
    boubleSort(array);        
    printArray(array);      
}

The first function prints out the array in its unsorted form, the second one sorts the array and then prints the sorted array. The third line prints the original array (which should remain unsorted) as sorted. Why odes this occur and how can I change this?

public static void boubleSort(int[] array) {
    System.out.println("Bouble Sort");
    int [] arr = array;
    
    for(int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
        for (int i = 0; i < lastUnsortedIndex;i++) {
            if(arr[i] < arr[i+1]) {
                swap(arr,i, i+1);
            }
        }
    }
    printArray(arr);
}

public static void swap(int [] array, int i, int j) {        
    if (i == j) {
        return;
    }       
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;       
}

public static void printArray(int [] arr) {    
    for(int i = 0; i < arr.length; i++) {
        System.out.println(arr[i]);
    }
    System.out.println();
}

Current output:          Desired output:

20                       20
35                       35
-15                      -14
7                        7
55                       55
1                        1
-2                       -2

Bouble Sort
35                       35
20                       20
7                        7
1                        1
-2                       -2
-15                      -15

20                       20
35                       35
-15                      -14
7                        7
55                       55
1                        1
-2                       -2
Vasko Vasilev
  • 554
  • 1
  • 10
  • 25
  • 2
    You need to manually create a copy of the input array and then use that. – f1sh Jul 02 '20 at 14:04
  • 1
    Java _IS_ pass by value. However, what you're passing (by value) is the _reference_ to the array. If you're from C, think 'pointer'. You make a copy of the reference, which is referencing the exact same array. Hence why your answer was marked as a duplicate of: "How do I make a copy of an array". – rzwitserloot Jul 02 '20 at 14:06
  • I see, so the following line: int [] arr = array was passing the reference to the array, leading to the algorithm making changes to that array. Is this correct? Changing that line to int [] arr = Arrays.copyOf(array, array.length). Solved my problem. – Vasko Vasilev Jul 02 '20 at 14:11

0 Answers0