Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java sắp xếp mảng theo thứ tự từ điển (Lexicographical Order)


Trong bài viết này, chúng ta sẽ tìm hiểu cách sắp xếp các phần tử của mảng theo thứ tự từ điển (lexicographical order) trong Java. Thứ tự từ điển là sự khái quát hóa của thứ tự bảng chữ cái trong từ điển cho các chuỗi.

Dưới đây là minh họa:

Đầu vào

Giả sử đầu vào:

Alpha Beta Gamma Delta

Đầu ra

Kết quả mong đợi:

Alpha Beta Delta Gamma

Thuật toán

Bước 1 - BẮT ĐẦU
Bước 2 - Khai báo ba số nguyên: i, j, array_length
Bước 3 - Khai báo mảng chuỗi
Bước 4 - Nhập array_length từ người dùng hoặc định nghĩa trước
Bước 5 - Nhập các từ của mảng chuỗi hoặc định nghĩa trước
Bước 6 - Chạy vòng lặp for, dùng phương thức swap và compareTo để sắp xếp. Lưu giá trị.
Bước 7 - Hiển thị kết quả
Bước 8 - DỪNG

Ví dụ 1: Sắp xếp mảng chuỗi định nghĩa trước

public class Main {
    public static void main(String[] args) {
        String[] my_input = {"Alpha", "Beta", "Gamma", "Delta"};
        int i, j, array_length;
        array_length = 4;
        System.out.println("The array of string is defined as");
        for (i = 0; i < array_length; i++) {
            System.out.println(my_input[i]);
        }
        for (i = 0; i < array_length - 1; ++i) {
            for (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 (i = 0; i < 4; i++) {
            System.out.println(my_input[i]);
        }
    }
}

Đầu ra

The array of string is defined as
Alpha
Beta
Gamma
Delta
The words in lexicographical order is:
Alpha
Beta
Delta
Gamma

Ví dụ 2: Sắp xếp không phân biệt chữ hoa thường

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[] = {"Alpha", "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);
    }
}

Đầu ra

Required packages have been imported
The Lexicographical Order data is
Alpha Beta Delta Gamma