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:
- What's the point of
var index = elements.size - 2, taking away 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--;
}
}