ในการเรียงลำดับคำในประโยคจากน้อยไปหามาก รหัส Java มีดังต่อไปนี้ −
ตัวอย่าง
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]+" ");
}
} ผลลัพธ์
The sorted array is : a is This sample
คลาสชื่อ Demo มีฟังก์ชันชื่อ 'sort_elements' ฟังก์ชันนี้จะวนซ้ำผ่านสตริง และตรวจสอบความยาวของทุกคำในสตริง และจัดเรียงตามความยาวของคำ ในฟังก์ชันหลัก อาร์เรย์ aString ถูกกำหนดและความยาวถูกกำหนดให้กับตัวแปร ฟังก์ชัน 'sort_elements' ถูกเรียกใช้บนสตริงนี้ และอาร์เรย์ที่จัดเรียงจะแสดงบนคอนโซล