示例: 按字典顺序对字符串进行排序的程序
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) { // 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]); } } }
输出
In lexicographical order: C Java Python Ruby
在上面的例子中,我们创建了一个名为
words 的
String
数组。该数组包含 5 个元素。
这里,我们使用
for
循环访问和比较每个数组元素
compareTo()
方法进行比较
由于我们按字典(字典)顺序对元素进行排序,如果字典中的第一个元素在第二个元素之后,我们将交换元素。
这是在每次迭代中比较和交换元素的方式。
Initial words | i | j | Comparison | word[] |
{ "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" } |