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的函数。这个函数遍历一个字符串,检查字符串中每个单词的长度,并根据它们的长度对它们进行排列。在main函数中,定义了aString数组并将其长度分配给一个变量。对该字符串调用sort_elements函数,排序后的数组将显示在控制台上。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短