Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java เรียงลำดับอาร์เรย์แบบ Lexicographical (Dictionary Order)

ในบทความนี้ เราจะเรียนรู้วิธีเรียงลำดับอาร์เรย์สตริงแบบ Lexicographical Order (แบบพจนานุกรม) ในภาษา Java

ตัวอย่างการทำงาน

อินพุต:

Aplha Beta Gamma Delta

เอาต์พุต:

Aplha Beta Delta Gamma

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปร index i, j, array_length และอาร์เรย์สตริง
  3. รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. ใช้ลูป for ซ้อนกันเปรียบเทียบด้วย compareTo() สลับตำแหน่งถ้าจำเป็น
  5. แสดงผลลัพธ์
  6. จบโปรแกรม

ตัวอย่างที่ 1: ใช้ compareTo (Case-sensitive)

public class Main {
    public static void main(String[] args) {
        String[] my_input = {"Aplha", "Beta", "Gamma", "Delta"};
        int array_length = 4;

        System.out.println("The array of string is defined as:");
        for (int i = 0; i < array_length; i++) {
            System.out.println(my_input[i]);
        }

        // Bubble sort ด้วย compareTo
        for (int i = 0; i < array_length - 1; ++i) {
            for (int j = i + 1; j < array_length; ++j) {
                if (my_input[i].compareTo(my_input[j]) > 0) {
                    String temp = my_input[i];
                    my_input[i] = my_input[j];
                    my_input[j] = temp;
                }
            }
        }

        System.out.println("The words in lexicographical order is:");
        for (int i = 0; i < array_length; i++) {
            System.out.println(my_input[i]);
        }
    }
}

ตัวอย่างที่ 2: ใช้ compareToIgnoreCase และแยกเมธอด

import java.io.*;

public class LexicographicalOrder {
    public static void sortData(String my_array[]) {
        for (int i = 0; i < my_array.length; i++) {
            for (int j = i + 1; j < my_array.length; j++) {
                if (my_array[i].compareToIgnoreCase(my_array[j]) > 0) {
                    String my_temp = my_array[i];
                    my_array[i] = my_array[j];
                    my_array[j] = my_temp;
                }
            }
        }
    }

    public static void printData(String my_array[]) {
        for (String my_string : my_array) {
            System.out.print(my_string + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        String my_array[] = {"Aplha", "Beta", "Gamma", "Delta"};
        System.out.println("Required packages have been imported");
        System.out.println("The Lexicographical Order data is");
        sortData(my_array);
        printData(my_array);
    }
}

หมายเหตุ

  • compareTo(): เปรียบเทียบแบบ case-sensitive (ตัวใหญ่/เล็กมีผล)
  • compareToIgnoreCase(): เปรียบเทียบไม่สนใจ case
  • ในทางปฏิบัติควรใช้ Arrays.sort() ซึ่งมีประสิทธิภาพดีกว่า