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; } }
bubbleSortYou can callinputArrininputArrand writeint[] arr = inputArr.clone();at the very beginning of the method, before the loopint[] arr = inputArr.clone();orint[] 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