Java程序按字典顺序对元素进行排序
在此程序中,您将学习使用for循环以及如果使用Java,则按字典顺序对元素词进行排序。
示例:按字典顺序对字符串排序的程序
public class Sort {
public static void main(String[] args) {
String[] words = { "Ruby", "C", "Python", "Java" };
for(int i = 0; i
for (int j = i + 1; 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
System.out.println(words[i]);
}
}
}
运行该程序时,输出为:按照字典顺序:
C
Java
Python
Ruby
在上面的程序中,要排序的5个单词的列表存储在变量word中。
然后,我们遍历每个单词(words [i]),并将其与数组中之后的所有单词(words [j])进行比较。这是通过使用字符串的compareTo()方法完成的。
如果compareTo()的返回值大于0,则必须在位置上进行交换,即word [i]在word [j]之后。 因此,在每次迭代中,单词[i]包含最早的单词执行步骤迭代初始词ijwords[]1{ "Ruby", "C", "Python", "Java" }01{ "C", "Ruby", "Python", "Java" }
2{ "C", "Ruby", "Python", "Java" }02{ "C", "Ruby", "Python", "Java" }
3{ "C", "Ruby", "Python", "Java" }03{ "C", "Ruby", "Python", "Java" }
4{ "C", "Ruby", "Python", "Java" }12{ "C", "Python", "Ruby", "Java" }
5{ "C", "Python", "Ruby", "Java" }13{ "C", "Java", "Ruby", "Python" }
Final{ "C", "Java", "Ruby", "Python" }23{ "C", "Java", "Python", "Ruby" }