java 陣列問題!!

小弟來求問了!!老師有給例題 然後叫我們做題目 請求大大們解題(兩種方式的程式碼都需要)

將5筆資料儲存於陣列中將其大至小或小至大排列輸入13,5,39,17,28,

例題 public class N9819142 { public static void main(String args[]) { int[] array = { 13, 5, 39, 17, 28 }; System.out.println("未排序的陣列"); for (int i = 0; i < array.length; i++) { System.out.print(" " + array[i]); if ((i + 1) % 5 == 0) System.out.println(); } int mid; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { if (array[j] < array[i]) { mid = array[i]; array[i] = array[j]; array[j] = mid; } } } System.out.println("\n 反昇:"); for (int i = 0; i < array.length; i++) { System.out.print(" " + array[i]); if ((i + 1) % 5 == 0) System.out.println(); } } }

1 Answer

Rating
  • 9 years ago
    Favorite Answer

    提供你兩種方式

    第一種氣泡排序法

    public class N9819142 {

    public static void main(String args[]) {

    int[] array = { 13, 5, 39, 17, 28 };

    System.out.print("未排序的陣列");

    for (int i = 0; i < array.length; i++) {

    System.out.print(" " + array[i]);

    }

    int n = array.length ;

    int t ;

    for (int i=n-2 ; i>=0 ; i--){

    for(int j=0 ; j<=i ; j++){

    if (array[j] > array[j + 1]){

    t = array[j];

    array[j] = array[j + 1];

    array[j + 1] = t;

    }

    }

    }

    System.out.println() ;

    System.out.print("由小到大排序:");

    for(int i=0 ; i<array.length ; i++){

    System.out.print(" " + array[i]) ;

    }

    System.out.print("\n由大到小排序:");

    for (int i = array.length-1; i >=0; i--) {

    System.out.print(" " + array[i]);

    }

    }

    }

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    第二種使用 Arrays類別中的 sort的方法(須引入Arrays類別)

    import java.util.Arrays; //引入Arrays類別

    public class N9819143 {

    public static void main(String args[]) {

    int[] array = { 13, 5, 39, 17, 28 };

    System.out.print("未排序的陣列");

    for (int i = 0; i < array.length; i++) {

    System.out.print(" " + array[i]);

    }

    System.out.println();

    System.out.print("由小到大排序:");

    Arrays.sort(array); //使用Arrays.sort(陣列變數名稱)將元素由小到大排列

    for (int i = 0; i < array.length; i++) {

    System.out.print(" " + array[i]);

    }

    System.out.print("\n由大到小排序:");

    for (int i = array.length-1; i >=0; i--) {

    System.out.print(" " + array[i]);

    }

    }

    }

    Source(s): 加菲貓
Still have questions? Get your answers by asking now.