LoginSignup
1
0

More than 3 years have passed since last update.

シェルソート

Posted at

メリット

処理速度が速い

ShellSort.java

class ShellSort{

  public static void main(Srring[] args){

   //ソート前の配列
   int a[] = {10,4,2,1,3,8,5,6,};

   //グループ分けの間隔を半分にしていく繰り返し
   for(int step = a.length / 2 ; step > 0; sttep /= 2){
      // 間隔を開けて挿入ソート
      // 配列から順番に1つずつ「挿入する値」を取り出すことを繰り返す
      for(int i = step; i < a.length ; i++){
         //挿入する値を変数に入れて退避
         int tmp = a[i];
         // 取り出した位置から前に向かって比較を繰り返す
         int j = i ;
         for (j = i ; j >= step; j -= step){
            //もし挿入する値が小さければその値をステップ幅だけ後ろへずらす
            a[j] = a[j-step];
         } else {
           //もし挿入する値が小さくなければ、そこでずらす処理を止める
           break;
         }
       }
       //ずらす処理が終わったところに「挿入する値」を入れる
       a[j] = tmp;
     }
   }
   //ソート後の配列の表示
   for (int i:a){
      System.out.println(i);
   }  
 }
}

参考書籍
楽しく学ぶアルゴリズムとプログラミングの図鑑

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0