0

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]);
    }
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
ezrnew
  • 1

3 Answers3

0

Because tempArr=array sets the pointer of tempArr to point to the same place in memory where array sits.

riorio
  • 6,500
  • 7
  • 47
  • 100
0

In java assigning one object to another doesn't copy the values of the object. It points both handles to the same object. If you want to copy values you can use the funcion clone()

sirine
  • 26
  • 2
0

This is an issue of reference Id. Because both are carrying the same reference id. You can use clone method of Object class.

Something like int[] tempArr = array.clone();

Rahul Kumar
  • 362
  • 1
  • 7