2

I have a 10x loop to sort an array of numbers B(copy of original array A) and record the run-time, since the array gets sorted at the end of a loop i created a duplicate array B to be changed and use A to set it to it's original state at the begin of a new loop.

when it sorts B, A automatically gets sorted too even though i only send B . why does this happen and how to change it?

loop:

for (i in 1..10) {
        val B = A
        val time = measureTimeMillis {
                val sorting = Insertion(B); sorting.sor
        }
        println(""+ cycle++ + "\t" + time)
}

sort:

class Insertion(var B: IntArray) {
    fun sort(): Unit {
        for( j in 1 until B.size){
            var key = B[j]
            var i = j-1
            while( i > -1 && B[i] > key){
                B[i+1] = B[i]
                i= i - 1
            }
            B[i+1] = key
        }
    }
}
Shankar
  • 417
  • 1
  • 6
  • 17

2 Answers2

2

It happens because you use the same array. After val B = A B is a reference to array A, no copy was created. To create a copy you need to call val B = A.copyOf().

Andrew Churilo
  • 2,229
  • 1
  • 17
  • 26
2

At the start of your loop, you have an IntArray object, and a variable which refers to it:

    A ──→ IntArray

You then create a second variable which refers to the same IntArray object.

    A
      >─→ IntArray
    B 

Hopefully this illustrates why changes made through the reference B will also be visible through the reference A.

If you want B to refer to a different IntArray, you'll have to make a copy of it, e.g.:

val B = A.copyOf()

or:

val B = A.clone()

or:

val B = IntArray(a.size){ A[it] }

or various other ways.  (copyOf() is usually the best.)

(Finally, please note that the Kotlin convention is for variables, methods, and properties to start with a lower-case letter, and only classes and type parameters to start with a capital.)

gidds
  • 16,558
  • 2
  • 19
  • 26
  • thank you it works perfectly, now i see that i have another issue. the time always gives me 0 in milliseconds – Pedro Parreira Apr 02 '19 at 15:08
  • @PedroParreira, it's surprisingly hard to get an idea of how long code can take to run.  See e.g. https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – gidds Apr 02 '19 at 15:25