Created
May 29, 2021 18:21
-
-
Save salif/341bcb9eaaa8479cde11785f8db88630 to your computer and use it in GitHub Desktop.
Kotlin sort Array<Int>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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