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

Chương trình Java sắp xếp từ của câu theo thứ tự tăng dần


Để sắp xếp từ của câu theo thứ tự tăng dần, mã Java như sau:

Ví dụ

import java.util.*; public class Demo{    static void sort_elements(String []my_str, int n){       for (int i=1 ;i<n; i++){          String temp = my_str[i];          int j = i - 1;          while (j >= 0 && temp.length() < my_str[j].length()){             my_str[j+1] = my_str[j];             j--;          }          my_str[j+1] = temp;       }    }    public static void main(String args[]){       String []my_arr = {"This", "is", "a", "sample"};       int len = my_arr.length;       sort_elements(my_arr,len);       System.out.print("The sorted array is : ");       for (int i=0; i<len; i++)       System.out.print(my_arr[i]+" ");    } }

Kết quả

The sorted array is : a is This sample

Lớp Demo chứa hàm sort_elements. Hàm lặp qua chuỗi kiểm tra độ dài mỗi từ và sắp xếp dựa trên độ dài. Trong main, mảng chuỗi định nghĩa, độ dài gán biến. Hàm sort_elements gọi trên chuỗi, mảng sắp xếp hiển thị.