I want to sort temporary array (tempArr
) in method in order to display k
values but I want the main array (array
) to stay unsorted. For some reason I dont understand when I do this tempArr=array;
and then use only tempArray
in while loop array is being sorted aswell. What is the reason?
public static void kLargestNums(int[] array, int k) {
int[] tempArr;
tempArr = array;
int liczba;
int a;
do {
liczba = 0;
for (int i = 0; i < tempArr.length - 1; i++) {
if (tempArr[i] < tempArr[i + 1]) {
a = tempArr[i];
tempArr[i] = tempArr[i + 1];
tempArr[i + 1] = a;
liczba++;
}
}
} while (liczba != 0);
for (int i = 0; i < k; i++) {
System.out.println(tempArr[i]);
}
}