Created
June 14, 2019 21:35
-
-
Save blakelee/577c0c09430b38a000dc1ba24334d36a to your computer and use it in GitHub Desktop.
Sort By swapWithA
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 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