利用Arrays工具提供的sort()方法实现数组排序
升序
public class Taks02 {
public static void main(String[] args) {
// 声明部分
int [] arr = {71, 54, 58, 29, 31, 78, 2, 77, 82};
System.out .print("原始数组:");
for (int x : arr) {
System.out.print(x + "\t");
}
System.out.println();
//调用Arrays类的sort()方法排序,默认是升序
Arrays.sort(arr);
System.out.print("升序排列: " );
for (int x : arr){
System.out.print(x + "\t");
}
System.out.println();
}
}
降序
public class Taks02 {
public static void main(String[] args) {
// 声明部分
int [] arr = {71, 54, 58, 29, 31, 78, 2, 77, 82};
System.out .print("原始数组:");
for (int x : arr) {
System.out.print(x + "\t");
}
System.out.println();
//调用Arrays类的sort()方法排序,默认是升序
Arrays.sort(arr);
System.out.print("升序排列: " );
for (int x : arr){
System.out.print(x + "\t");
}
System.out.println();
//调用Arrays类的sort()方法降序排列
Arrays.sort( arr, Collections.reverseOrder());
System.out.print("降序排列:");
for (int x: arr) {
System.out.print(x + "\t");
}
}
}