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