# Merge Sort in Scala printing a garbage output

I have written a program on mergesort in Scala. I used the following three functions:

1. splitArray – Splits the given array in two sub-arrays (leftArray, rightArray)
2. merge – merges sub-arrays
3. sort – sorts sub-arrays

When I try to run the program, it compiles but it returns a garbage output instead of returning a sorted array.

``````    (I@28864e92
Process finished with exit code 0
``````

The splitArray and merge functions work fine when I tested them by running a code using these two functions separately. My assumption is that there is an issue in my sort function, which I am not aware of.

It’d be much appreciated if anyone takes a look where I am doing wrong.

``````object Exercises {
def main(args: Array(String)): Unit = {

var arr = Array(5,3,10,5,6,1,3)
print(sort(arr) + " ")

def splitArray(a : Array(Int)) : (Array(Int),Array(Int)) = {
var half : Int = Math.floor(a.length / 2).toInt
var firstHalf : Array(Int) = a.slice(0,half)
var secondHalf : Array(Int) = a.slice(half, a.length)

(firstHalf, secondHalf)
}

def merge(a : Array(Int), b : Array(Int)) : Array(Int) = {
var i, j, k : Int = 0
var c : Array(Int) = new Array(Int)(a.length + b.length)

while(i < a.length && j < b.length) {
if (a(i) < b(j)) {
c(k) = a(i)
i = i + 1
}
else {
c(k) = b(j)
j = j + 1
}
k = k + 1
}
while (i < a.length) {
c(k) = a(i)
i = i + 1
k = k + 1
}
while (j < b.length) {
c(k) = b(j)
j = j + 1
k = k + 1
}
c
}

def sort(a : Array(Int)) : Array(Int) = {
var n : Int = a.length
if(n < 2) {
a
}
else {
var (leftArr, rightArr) = (splitArray(a))
sort(leftArr)
sort(rightArr)
merge(leftArr, rightArr)
}
}
}
}
``````