English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestione delle eccezioni Java

Java 列表(List)

Java 队列(Queue)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

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

Esempi completi di Java

在此程序中,您将学习使用for循环以及如果使用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

Nell'esempio sopra, l'elenco di 5 parole da ordinare è memorizzato nella variabile word.

Poi, esaminiamo ogni parola (words [i]) e la confrontiamo con tutte le altre parole (words [j]) successive nell'array. Questo viene fatto utilizzando il metodo compareTo() della stringa.

Se il valore di ritorno di compareTo() è maggiore di 0, devono essere effettuati scambi in posizione, ovvero word [i] dopo word [j]. Pertanto, in ogni iterazione, la parola [i] contiene la parola più antica

Passaggi di esecuzione
IterazioneParola inizialeijwords[]
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"}
Finale{"C", "Java", "Ruby", "Python"}23{"C", "Java", "Python", "Ruby"}

 

Esempi completi di Java