public class ArrayRefDemo03{
public static void main(String args[]){
int score[] = {67,89,87,69,90,100,75,90} ; // 定义整型数组
int age[] = {31,30,18,17,8,9,1,39} ; // 定义整型数组
sort(score) ; // 数组排序
print(score) ; // 数组打印
System.out.println("\n---------------------------") ;
sort(age) ; // 数组排序
print(age) ; // 数组打印
}
public static void sort(int temp[]){ // 执行排序操作
for(int i=1;i<temp.length;i++){
for(int j=0;j<temp.length;j++){
if(temp[i]<temp[j]){
int x = temp[i] ;
temp[i] = temp[j] ;
temp[j] = x ;
}
}
}
}
public static void print(int temp[]){ // 输出数组内容
for(int i=0;i<temp.length;i++){
System.out.print(temp[i] + "\t") ;
}
}
};
以上只是完成了整型数组的排序操作,如果一个操作中即要求可以排序整型也可以排序浮点型等各种数据,如果分别实现会比较麻烦,所以在Java中为了对数组操作方便,提供了一种支持。
public class ArrayRefDemo04{ public static void main(String args[]){ int score[] = {67,89,87,69,90,100,75,90} ; // 定义整型数组 int age[] = {31,30,18,17,8,9,1,39} ; // 定义整型数组 java.util.Arrays.sort(score) ; // 数组排序 print(score) ; // 数组打印 System.out.println("\n---------------------------") ; java.util.Arrays.sort(age) ; // 数组排序 print(age) ; // 数组打印 } public static void print(int temp[]){ // 输出数组内容 for(int i=0;i<temp.length;i++){ System.out.print(temp[i] + "\t") ; } } };