数组排序（冒泡法）

站长推荐：程序员必备10TBJava大数据机器学习人工智能从入门到精通视频教程下载

CODE:

import java.util.Scanner;

public class ArySort {

/**
* @param args
*/
//排序(降序)
public static int[] sort(int[] ary){
for (int i = 1; i < ary.length; i++) {
for (int j = 0; j < ary.length-i; j++) {
if(ary[j] < ary[j+1]){
int temp = ary[j];
ary[j] = ary[j+1];
ary[j+1] = temp;
}
}
}
return ary;
}

// 数组倒置
public static int[] swap(int[] ary){
for (int i = 0,j = ary.length-1; i < ary.length/2; i++,j--) {
int temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
}
return ary;
}
// 打印数组
public static void printAry(int[] ary){
for (int i = 0; i < ary.length; i++) {
System.out.print(ary[i]+"\t");
}
}
public static void main(String[] args) {
Scanner ss = new Scanner(System.in);
System.out.print("请输入数组长度：");
int len = ss.nextInt();
if(len < 0){
System.out.println("数组长度有误！");
return;
}
int[] ary = new int[len];
for(int i = 0; i < ary.length;i++){
System.out.println("请输入第"+(i+1)+"数据：");
ary[i] = ss.nextInt();
}
System.out.println("排序前的数组为：");
printAry(ary);
sort(ary);
System.out.println();
System.out.println("1.升序， 2.降序");
int a = ss.nextInt();
if(a == 1){
swap(ary);
}
System.out.println("排序后的数组为：");
printAry(ary);
System.out.println();
}

}