在此程序中,您將學習使用for循環(huán)以及如果使用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) { // 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
在上面的程序中,要排序的5個單詞的列表存儲在變量word中。
然后,我們遍歷每個單詞(words [i]),并將其與數(shù)組中之后的所有單詞(words [j])進行比較。這是通過使用字符串的compareTo()方法完成的。
如果compareTo()的返回值大于0,則必須在位置上進行交換,即word [i]在word [j]之后。 因此,在每次迭代中,單詞[i]包含最早的單詞
迭代 | 初始詞 | i | j | words[] |
---|---|---|---|---|
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" } |
Final | { "C", "Java", "Ruby", "Python" } | 2 | 3 | { "C", "Java", "Python", "Ruby" } |