Skip to content

Instantly share code, notes, and snippets.

@blakelee
Created June 14, 2019 21:35
Show Gist options
  • Select an option

  • Save blakelee/577c0c09430b38a000dc1ba24334d36a to your computer and use it in GitHub Desktop.

Select an option

Save blakelee/577c0c09430b38a000dc1ba24334d36a to your computer and use it in GitHub Desktop.
Sort By swapWithA
fun main() {
val arr = ('a'..'z').shuffled().toTypedArray()
var aPos = arr.indexOf('a')
fun swapWithA(char: Char) {
val charPos = arr.indexOf(char)
arr[charPos] = 'a'
arr[aPos] = char
aPos = charPos
}
fun sortBySwapWithA(arr: Array<Char>) {
var pos = 1
while(pos < 26) {
val cur = arr[pos]
if (cur - 'a' == pos) {
pos++
continue
} else {
swapWithA(cur)
swapWithA('a' + pos) // a is here
}
}
}
sortBySwapWithA(arr)
println(arr.joinToString())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment