迴歸基礎系列-選擇排序[JAVA]

選擇排序:
基本思想:選擇排序基本思想:選擇出一個最大(最小)每次放在已排好的數組最後面。

/**
 * 選擇排序
 * @author Ant
 *
 */
public class SelectSort {
    /**
     * 選擇排序基本思想:選擇出一個最大(最小)每次放在已排好的數組最後面。
     * @param a
     */
    public static void selectSort(int a[]){
        int k;//專門存最大(最小)的數的下標
        for(int i = 0; i < a.length-1; i++){
            k = i;
            for(int j = i + 1; j < a.length; j++){
                if(a[k] < a[j]){//尋找最大的數的下標
                    k = j;
                }
            }

            if(k!=i){
                int temp = a[i];
                a[i] = a[k];
                a[k] = temp;
            }
        }
    }

    public static void main(String[] args) {
        int a [] = {11,38, 24, 10, 3, 5, 18};
        InsertSort.insertSort(a);
        for(int i = 0; i < a.length; i++){
            System.out.println(a[i]+" ");
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章