문장의 단어를 오름차순으로 정렬하려면 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' 함수가 호출되고 정렬된 배열이 콘솔에 표시됩니다.