# Java 程序：按字典顺序对元素进行排序

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

#### 在此程序中，您将学习使用`for`循环以及`if-else`按字典顺序对元素词进行排序。

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

```java
public class Sort {

    public static void main(String[] args) {
        String[] words = { "Ruby", "C", "Python", "Java" };

        for(int i = 0; i < 3; ++i) {
            for (int j = i + 1; j < 4; ++j) {
                if (words[i].compareTo(words[j]) > 0) {

                    // swap words[i] with words[j[
                    String temp = words[i];
                    words[i] = words[j];
                    words[j] = temp;
                }
            }
        }

        System.out.println("In lexicographical order:");
        for(int i = 0; i < 4; i++) {
            System.out.println(words[i]);
        }
    }
}
```

运行该程序时，输出为：

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

在上述程序中，要排序的 5 个单词的列表存储在变量`word`中。

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

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

执行步骤

| 迭代 | 初始词 | `i` | `j` | `word[]` |
| --- | --- | --- | --- | --- |
| 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" }` |