I have the array A = arrayOf(Pair(1,1),Pair(0,9),Pair(3,8),Pair(4,0),Pair(6,6),Pair(10,7),Pair(5,1),Pair(7,3))
in Kotlin and I want to sort it with mergesort based on the X component of the pairs.
So far I have this
fun merge(U: Array<Pair<Int,Int>>, V: Array<Pair<Int,Int>>, A: Array<Pair<Int,Int>>) {
var i: Int = 0
var j: Int = 0
var size = U.size + V.size
for (k in 0 until size) {
if ((i < U.size)&&(j < V.size)) {
if (U[i].component1() < V[i].component1()) {
A[k] = U[i]
i = i + 1
}
else {
A[k] = V[j]
j = j + 1
}
}
}
}
fun mergeSort(A: Array<Pair<Int,Int>>) {
var middle = A.size / 2
var U = A.copyOfRange(0, middle)
var V = A.copyOfRange(middle, A.size)
mergeSort(U)
mergeSort(V)
merge(U, V, A)
}
However, it gives me a stackoverflow error. I don't know what could be the cause of it. Is there a better way to do this?
edit: @ggorlen pointed out that I was missing the base case, which after checking, I had accidentally deleted while modifying the mergesort function. Thanks!