[JAVA]選擇排序(SelectionSort):小到大

選擇排序(SelectionSort)

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class SelectionSort {



  public static void main(String[] args) {
//   int[] array = {-1,3,2,10,9,-2};
//   System.out.println("交換前陣列=" + Arrays.toString(array));
//   doSelectionSorting(array);
//   System.out.println("交換後陣列=" + Arrays.toString(array));

    int n = 80000;
    int[] array = new int[n];
    for (int i = 0; i < array.length; i++) {
      array[i] = (int) (Math.random() * 800000);
    }

    Date beforeTime = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String beforeTimeStr = sdf.format(beforeTime);
    System.out.println("選擇排序前:" + beforeTimeStr);
    doSelectionSorting(array);
    Date afterTime = new Date();
    String afterTimeStr = sdf.format(afterTime);
    System.out.println("選擇排序後:" + afterTimeStr);

  }

  /**
   * 選擇排序
   * 外層迴圈循環次數array.lenth-1
   * @param array
   */
  public static void doSelectionSorting(int[] array) {



    for (int i = 0; i < array.length-1; i++) {
      // 先假設陣列第一個索引與值都是最小
      // 隨著陣列前面的數位置確定下來,minInx隨循環後移進行比較
      int minInx = i;
      int min = array[i];

       for (int j = 1+i ; j < array.length; j++) {
         if (min > array[j]) {
           // 重設minInx, min
           minInx = j;
           min = array[j];
         }
       }
       // 兩值必須交換
       if (minInx != i) {
         array[minInx] = array[i];
         array[i] = min;
       }
    }

  }
}

如有敘述錯誤,還請不吝嗇留言指教,thanks!