92.md 2.2 KB
Newer Older
W
wizardforcel 已提交
1
# Kotlin 程序:按字典顺序对元素进行排序
W
wizardforcel 已提交
2 3 4

> 原文: [https://www.programiz.com/kotlin-programming/examples/lexicographical-order-words](https://www.programiz.com/kotlin-programming/examples/lexicographical-order-words)

W
wizardforcel 已提交
5
#### 在此程序中,您将学习使用`for`循环和 Kotlin 中的`if`循环按字典顺序对元素词进行排序。
W
wizardforcel 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

## 示例:按字典顺序对字符串排序的程序

```kt
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) {

                // swap words[i] with words[j[
                val temp = words[i]
                words[i] = words[j]
                words[j] = temp
            }
        }
    }

    println("In lexicographical order:")
    for (i in 0..3) {
        println(words[i])
    }
}
```

运行该程序时,输出为:

```kt
In lexicographical order:
C
Java
Python
Ruby
```

W
wizardforcel 已提交
43
在上述程序中,要排序的 5 个单词的列表存储在变量`word`中。
W
wizardforcel 已提交
44

W
wizardforcel 已提交
45
然后,我们遍历每个单词(`words[i]`),并将其与数组中之后的所有单词(`words[j]`)进行比较。 这是通过使用字符串的`compareTo()`方法完成的。
W
wizardforcel 已提交
46

W
wizardforcel 已提交
47
如果`compareTo()`的返回值大于 0,则必须在位置上进行交换,即`word[i]``word[j]`之后。 因此,在每次迭代中,`words[i]`包含最早的单词。
W
wizardforcel 已提交
48

W
wizardforcel 已提交
49 50
Execution Steps

W
wizardforcel 已提交
51
| 迭代 | 初始单词 | `i` | `j` | `words[]` |
W
wizardforcel 已提交
52 53 54 55 56 57 58 59 60
| --- | --- | --- | --- | --- |
| 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 程序](/java-programming/examples/lexicographical-order-words "Java program to sort words in lexicographical order")