思路:定義了三個(gè)方法分別是sort、swap、PRintAry,分別執(zhí)行排序、數(shù)組倒置、打印數(shù)組的功能,定義倒置數(shù)組的目的呢,就是按照用戶的需要來打印出是升序還是降序的結(jié)果。
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;
}
// 數(shù)組倒置
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;
}
// 打印數(shù)組
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("請(qǐng)輸入數(shù)組長(zhǎng)度:");
int len = ss.nextInt();
if(len < 0){
System.out.println("數(shù)組長(zhǎng)度有誤!");
return;
}
int[] ary = new int[len];
for(int i = 0; i < ary.length;i++){
System.out.println("請(qǐng)輸入第"+(i+1)+"數(shù)據(jù):");
ary[i] = ss.nextInt();
}
System.out.println("排序前的數(shù)組為:");
printAry(ary);
sort(ary);
System.out.println();
System.out.println("1.升序, 2.降序");
int a = ss.nextInt();
if(a == 1){
swap(ary);
}
System.out.println("排序后的數(shù)組為:");
printAry(ary);
System.out.println();
}
}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注