Skip to content

Instantly share code, notes, and snippets.

@salif
Created May 29, 2021 18:21
Show Gist options
  • Save salif/341bcb9eaaa8479cde11785f8db88630 to your computer and use it in GitHub Desktop.
Save salif/341bcb9eaaa8479cde11785f8db88630 to your computer and use it in GitHub Desktop.
Kotlin sort Array<Int>
fun sort(array: Array<Int>): Array<Int> {
when {
array.size == 1 -> {
return array
}
array.size <= 2 -> {
val left = array[0]
val right = array[1]
return if (right < left) {
arrayOf(right, left)
} else {
arrayOf(left, right)
}
}
else -> {
val middle = array.size / 2
val left = sort(array.sliceArray(0 until middle))
val right = sort(array.sliceArray(middle until array.size))
val last = left[left.size - 1]
val first = right[0]
if (last > first) {
left[left.size - 1] = first
right[0] = last
return (sort(left.plus(right)))
}
return left.plus(right)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment