Kotlin 程序:按字典顺序排列元素
示例:按字典顺序排序字符串的程序
fun main(args: Array<String>) {
val words = arrayOf("Ruby", "C", "Python", "Java")
for (i in 0..2) {
for (j in i + 1..3) {
if (words[i].compareTo(words[j]) > 0) {
// 交换 words[i] 和 words[j]
val temp = words[i]
words[i] = words[j]
words[j] = temp
}
}
}
println("按字典顺序排序后:")
for (i in 0..3) {
println(words[i])
}
}
当你运行这个程序时,输出将会是:
按字典顺序排序后:
C
Java
Python
Ruby
在上面的程序中,待排序的单词列表存储在变量 words
中。
然后,我们遍历每个单词(words[i]
),并将其与数组中它后面的所有单词(words[j]
)进行比较。这是通过使用字符串的 compareTo()
方法实现的。
如果 compareTo()
的返回值大于0,就需要交换它们的位置,即 words[i]
排在 words[j]
之后。因此,在每次迭代中,words[i]
包含最早的单词。
执行步骤
迭代 | 初始单词 | i | j | words[] |
---|---|---|---|---|
1 | { "Ruby", "C", "Python", "Java" } | 0 | 1 | { "C", "Ruby", "Python", "Java" } |
2 | { "C", "Ruby", "Python", "Java" } | 0 | 2 | { "C", "Ruby", "Python", "Java" } |
3 | { "C", "Ruby", "Python", "Java" } | 0 | 3 | { "C", "Ruby", "Python", "Java" } |
4 | { "C", "Ruby", "Python", "Java" } | 1 | 2 | { "C", "Python", "Ruby", "Java" } |
5 | { "C", "Python", "Ruby", "Java" } | 1 | 3 | { "C", "Java", "Ruby", "Python" } |
最终 | { "C", "Java", "Ruby", "Python" } | 2 | 3 | { "C", "Java", "Python", "Ruby" } |
以下是等效的Java代码:Java程序:按字典顺序排序单词。