Skip to content

Instantly share code, notes, and snippets.

@JunJaBoy
Created April 26, 2024 04:22
Show Gist options
  • Save JunJaBoy/22dea3e1b2c5d3974966caf37cdf0f60 to your computer and use it in GitHub Desktop.
Save JunJaBoy/22dea3e1b2c5d3974966caf37cdf0f60 to your computer and use it in GitHub Desktop.
AlternativeSort
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