Home > Mobile >  Why doesn't this kotlin code throw out-of-bounds errors? [closed]
Why doesn't this kotlin code throw out-of-bounds errors? [closed]

Time:09-24

This is a sort function for an array - elements. After we add an item to the right of the elements, we call sort on it.


    sort() {
    var index = elements.size - 2
    while (index >= 0 &&
    elements[index   1].compareTo(elements[index]) > 0) {
    swap(index, index   1)
    index--;
    }
    }

Suppose I have this array: val array = ArrayList(). Now I add 1 to this array and every time I add an item I run sort on array. Cleary, we have:

    index = -1
    elements[1].compareTo(elements[-1])

The code compiles and runs correctly. I think that the biggest index == elements.size - 1 and the second largest == elements.size - 2, so I modified the code like this:


    sort() {
            var index = count
            while (index >= 0 &&
                elements[index - 1].compareTo(elements[index - 2]) > 0) {
                swap(index-1, index - 2)
                index--;
            }

Here's the error: "Index -1 out of bounds for length 1"

My questions:

  1. What's the point of var index = elements.size - 2, taking away 2.
  2. An out of bounds error in the second piece of code and not the original although both access array elements out of their bounds.

Update: This is my own modification, so I do not know if it reflects the intent of the author.


    sort(elements: ArrayList<Int>) {
    fun swap(i: Int, j: Int) {
        val tmp = elements[i]
        elements[i] = elements[j]
        elements[j] = tmp
      }
        var index = elements.size - 2
        while (index >= 0 &&
          elements[index   1].compareTo(elements[index]) > 0) {
          swap(index, index   1)
          index--;
        }
      }

  

CodePudding user response:

You clearly missed this check:

while (index >= 0

No, original code did not go out of bounds, because it didn't execute the code inside the loop for index = -1. Your code does and then it goes out of bounds. I didn't verify this, but I guess if you would modify this check as well as other places, so it would be: while (index >= 2 then your code would be fine.

The reason to subtract 2 is just to start sorting from the element that is second from the end. And inherently, it ignores empty and single-item arrays.

Also, it doesn't really look like a fully working sorting algorithm. It looks like a bubble sort, but you need to run this code several times in another loop.

  • Related