Java程序按字典顺序排列元素
要理解这个示例,您应该了解以下 Java 编程 主题:
示例:按字典顺序排序字符串
class Main {
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) {
// 交换 words[i] 和 words[j]
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
System.out.println("按字典顺序排列:");
for(int i = 0; i < 4; i++) {
System.out.println(words[i]);
}
}
}
输出
按字典顺序排列:
C
Java
Python
Ruby
在上述示例中,我们创建了一个名为 words
的 String
数组。该数组包含 4 个元素。
这里,我们使用
for
循环来访问和比较每个数组元素compareTo()
方法来进行比较
由于我们正在按字典(字典)顺序排序元素,如果第一个元素在字典中排在第二个元素之后,我们就交换元素。
以下是每次迭代中元素的比较和交换情况。
初始 words | i | j | 比较 | words[] |
---|---|---|---|---|
{ "Ruby", "C", "Python", "Java" } | 0 | 1 | Ruby 和 C | { "C", "Ruby", "Python", "Java" } |
{ "C", "Ruby", "Python", "Java" } | 0 | 2 | C 和 Python | { "C", "Ruby", "Python", "Java" } |
{ "C", "Ruby", "Python", "Java" } | 0 | 3 | C 和 Java | { "C", "Ruby", "Python", "Java" } |
{ "C", "Ruby", "Python", "Java" } | 1 | 2 | Ruby 和 Python | { "C", "Python", "Ruby", "Java" } |
{ "C", "Python", "Ruby", "Java" } | 1 | 3 | Python 和 Java | { "C", "Java", "Ruby", "Python" } |
{ "C", "Java", "Ruby", "Python" } | 2 | 3 | Ruby 和 Python | { "C", "Java", "Python", "Ruby" } |