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

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

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

Comprehensive Java examples

在此程序中,您将学习使用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
C
Java
Python

Ruby5In the above program, the words to be sorted are

The list of words is stored in the variable word.

Then, we traverse each word (words [i]) and compare it with all the words after it in the array (words [j]). This is done by using the compareTo() method of the string.

Execution steps. If the return value of compareTo() is greater than 0, it must be swapped in position, that is, word [i] after word [j]. Therefore, in each iteration, the word [i] contains the earliest word
IterationInitial wordijwords[]
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" }

 

Comprehensive Java examples