本篇博文最后修改时间:2016年3月1日,22:17。
本篇介绍2种数组排列方法。
系统版本:Windows7 家庭普通版 32位操作系统。
三、版权声明
博主:思跡
声明:喝水不忘挖井人,转载请注明出处。
原文地址:http://blog.youkuaiyun.com/omoiato
联系方式:315878825@qq.com
Java零基础入门交流群:541462902
四、数组排列
范例1:将数组程序修改成一个方法的调用形式
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 One = 1; One < temp.length; One++)
{
for (int Two = 0; Two < temp.length; Two++)
{
if(temp[One] < temp[Two])
{
int x = temp[One]; //交换位置操作
temp[One] = temp[Two];
temp[Two] = x;
}
}
}
}
public static void print(int temp[]) //输出数组内容
{
for(int One = 0; One < temp.length; One++)
{
System.out.print(temp[One] + "\t");
}
}
}
程序运行结果
:
范例2:使用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); //使用Java提供的排序操作
print(score); //输出数组
System.out.println("\n-----------------------------------------------------");
java.util.Arrays.sort(age); //使用Java提供的排序操作
print(age);
}
public static void print(int temp[]) //数组输出
{
for(int One = 1; One < temp.length; One++)
{
System.out.print(temp[One] + "\t");
}
}
}
程序运行结果
: