Created
April 26, 2024 04:22
-
-
Save JunJaBoy/22dea3e1b2c5d3974966caf37cdf0f60 to your computer and use it in GitHub Desktop.
AlternativeSort
This file contains hidden or 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 IntArray.alternateSort(): IntArray { | |
require(this.isNotEmpty()) { "There must be at least one element" } | |
this.sort() | |
val result = mutableListOf<Int>() | |
var j = this.lastIndex | |
var i = 0 | |
while (i < j) { | |
result.add(this[j--]) | |
result.add(this[i++]) | |
} | |
if (size % 2 != 0) { | |
result.add(this[i]) | |
} | |
return result.toIntArray() | |
} | |
fun main(args: Array<String>) { | |
val arr = intArrayOf(1, 12, 4, 6, 7, 10) | |
println(arr.alternateSort().asList()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment