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函数,排序后的数组将显示在控制台上。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下