Two Way Merge Sort

import java.util.*

fun main() {
    val arr = intArrayOf(2, 1, 4, 10).toTypedArray()
    val queue = LinkedList<Array<Int>>()
    arr.forEach {
        queue.offer(arrayOf(it))
    }
    while (queue.size > 1) {
        val left = queue.pop()
        val right = queue.pop()
        queue.offer(merge(left, right))
    }

    val sortedArray = if (queue.isNotEmpty()) {
        queue.first
    } else {
        arr
    }
    println("sorted: ${sortedArray.contentToString()}")
}

fun merge(left: Array<Int>, right: Array<Int>): Array<Int> {
    var leftIndex = 0
    var rightIndex = 0
    val result = Array(left.size + right.size) { 0 }
    for (index in result.indices) {
        when {
            leftIndex == left.size && rightIndex == right.size -> {
                break
            }

            leftIndex == left.size -> {
                result[index] = right[rightIndex++]
            }

            rightIndex == right.size && leftIndex < left.size -> {
                result[index] = left[leftIndex++]
            }

            left[leftIndex] < right[rightIndex] -> {
                result[index] = left[leftIndex++]
            }

            else -> {
                result[index] = right[rightIndex++]
            }
        }
    }
    return result
}

top