基本挿入法のサンプルコード
 引数で配列を渡すことによって、その配列を基本挿入法でソートするです。
 1:
 2:
 3:
 4:
 5:
 6:
 7:
 8:
 9:
 10:
 11:
 12:
 13:
 14:
 15:
 16:
 17:
 18:
 19:
 20:
 21:
 22:
 23:
 24:
 25:
 26:
 27:
 28:
 29:
 30:
 31:
 32:
 33:
 34:
 35:
 36:
class InsertSortTest{
    public static void main(String[] args){
        int[] arr = {8, 6, 2, 5, 4, 9, 1, 3, 0, 7};
        
        System.out.print("ソート前:");
        arrayPrintln(arr);
        
        insertSort(arr);

        System.out.print("ソート後:");
        arrayPrintln(arr);
    }

    //基本挿入法(インサートソート)***************
    public static void insertSort(int[] arr){
        int i,j;
        for(i=1; i<arr.length; i++){
            int tmp = arr[i];
            for(j= i-1; j>=0; j--){
                if(arr[j] < tmp){
                    break;
                }
                arr[j+1] = arr[j];
            }
            arr[j+1] = tmp;
        }
    }
    
    //配列の値を出力するメソッド*******************
    public static void arrayPrintln(int[] arr){
        for(int i=0; i<arr.length; i++){
            System.out.print(arr[i] + " ");
        }
        System.out.println("");
    }
}

TOPに戻る   Javaアルゴリズムに戻る