There was a problem when solving a problem on CodeAbbey . The program must sort the array and output for each element its sequence number in the source array. But in the 10th line, it also sorts the source array, which it should not do. What is this about, and how can the problem be solved?

import java.io.*; import java.util.*; public class Solution { static Scanner in = new Scanner(System.in); static int num = in.nextInt(); public static void main(String[] args) { int[] arr = fillArray(num); int[] sortedArr = bubbleSort(arr); // Сортирует исходный массив checkIndexes(sortedArr, arr); } static void checkIndexes(int[] sortedArr, int[] arr) { for (int i = 0; i < num; i++) { for (int k = 0; k < num; k++) { if (sortedArr[i] == arr[k]) { System.out.print((k + 1) + " "); } } } } static int[] bubbleSort(int[] arr) { while (true) { int swaps = 0; for (int i = 0; i < arr.length - 1; i++) { if (arr[i] >= arr[i + 1]) { int buff = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = buff; swaps++; } } if (swaps == 0) break; } return arr; } static int[] fillArray(int num) { int[] arr = new int[num]; for (int i = 0; i < num; i++) { arr[i] = in.nextInt(); } return arr; } } 
  • This is how java ¯ \ _ (ツ) _ / ¯ bubbleSort You can call inputArr in inputArr and write int[] arr = inputArr.clone(); at the very beginning of the method, before the loop int[] arr = inputArr.clone(); or int[] arr = Arrays.copyOf(inputArr, inputArr.length); then everything will work ........ I'm honestly too lazy to translate an article on this topic with enSO. you can see for yourself on stackoverflow.com/questions/12757841/… ........ maybe someone will later write why - Alex Shimansky
  • @ Alexey Shimansky Thank you, helped - ktototamov

1 answer 1

The specification clearly states

that an array type variable contains an object reference. Declaring an array type variable does not create an object or allocates space for the components of an array. It creates only the variable itself, which may contain an array reference.

A variable of array type holds a reference to an object. Declaring a variable of array type It creates only a reference to an array.

Thus, int[] fillArray(int num) returns a reference to an array. The value of this link is assigned to int[] arr = fillArray(num) variable arr , and then the value of this link is used by calling the bubbleSort(arr) method. That is, bubbleSort will refer to the array, which was created by the fillArray method, via this link.

To solve the problem, you can pass a link to a copy of the array. For example, int[] sortedArr = bubbleSort(Arrays.copyOf(arr, arr.length)) . Arrays.copyOf will create a new array and 'bubbleSort' will work with the link already to this new array.