import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
// int [] objs={3,6,1,10,8};
// objs=sort(objs);
String[] objs={"b","a","c","h","d"};
objs=sort(objs);
for (int i = 0; i < objs.length; i++) {
System.out.println(objs[i]+" ");
}
}
public static int[] sort(int[] nums){
Arrays.sort(nums);
return nums;
}
public static String[] sort(String[] strs){
for (int i = 0; i < strs.length; i++) {
for (int j = 0; j < strs.length-i-1; j++) {
if(strs[j].compareTo(strs[j+1])<1){
String temp=strs[j];
strs[j]=strs[j+1];
strs[j+1]=temp;
}
}
}
return strs;
}
}
追问:
可不可以帮我注明一下
追答:
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
//数字已经测试过,没有问题
// int [] objs={3,6,1,10,8};
// objs=sort(objs);
//随便建一个字符的数组
String[] objs={"b","a","c","h","d"};
objs=sort(objs);
//打印
for (int i = 0; i < objs.length; i++) {
System.out.println(objs[i]+" ");
}
}
//用Arrays.sort()方法排序,默认从小到大
public static int[] sort(int[] nums){
Arrays.sort(nums);
return nums;
}
//字符串排序,用冒泡排序,通过compareTo(str)方法进行比较,该方法是根据字典表的顺序进行比较,如果参数大于本值,则返回-1,如果相等返回0,大于返回1
public static String[] sort(String[] strs){
for (int i = 0; i < strs.length; i++) {
for (int j = 0; j < strs.length-i-1; j++) {
if(strs[j].compareTo(strs[j+1])<1){
String temp=strs[j];
strs[j]=strs[j+1];
strs[j+1]=temp;
}
}
}
return strs;
}
} |