按字母順序對 Java 中的單詞進行排序


這些單詞按字母順序或字典順序進行排序。這意味著將根據單詞中包含的字母按字母順序對單詞進行排序。以下給出了一個示例。

The original order of the words is
Tom
Anne
Sally
John
The lexicographical order of the words is
Anne
John
Sally
Tom

展示這一點的程式如下。

示例

 線上演示

public class Example {
   public static void main(String[] args) {
      String[] words = { "Peach", "Orange", "Mango", "Cherry", "Apple" };
      int n = 5;
      System.out.println("The original order of the words is: ");
      for(int i = 0; i < n; i++) {
         System.out.println(words[i]);
      }
      for(int i = 0; i < n-1; ++i) {
         for (int j = i + 1; j < n; ++j) {
            if (words[i].compareTo(words[j]) > 0) {
               String temp = words[i];
               words[i] = words[j];
               words[j] = temp;
            }
         }
      }
      System.out.println("
The lexicographical order of the words is: ");       for(int i = 0; i < n; i++) {          System.out.println(words[i]);       }    } }

輸出

The original order of the words is:
Peach
Orange
Mango
Cherry
Apple
The lexicographical order of the words is:
Apple
Cherry
Mango
Orange
Peach

更新於: 2020 年 6 月 25 日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告