9
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】バブルソートの実装

Last updated at Posted at 2016-01-21

動機

・処理速度を意識しながらコードをかけるようにとのことで、プログラムのアルゴリズムの復習もかねて、まずはバブルソートを実装を行った。

バブルソート

隣合う要素の大小を比較しながら、整列させること。計算時間が遅いが、アルゴリズムが単純で実装が容易なことと並列処理との親和性が高いことからしばしば用いられる安定な内部ソートのこと。

バブルソート実装コード
BubbleSortTest.java
public class BubbleSortTest {

    static void bubble_sort(int[] d) {
        // iはi回目の交換する回数
        for (int i = d.length-1; i > 0; i-- ) {
            // j は交換する箇所の前からの番号を示している
            for (int j = 0; j < i; j++) {
                if(d[j]>d[j+1]){
                  //降順にしたい場合は不等号を逆に
                  int box = d[j];
                  d[j] = d[j+1];
                  d[j+1] = box;
                  System.out.println(d[j] + ":" +d[j+1]);
                } else{
                  //そのまま
                }
            }
        }
    }
    static void print_data(int[] d) {
        for(int i = 0; i < d.length; i++) System.out.print(d[i] + " ");
    }
    public static void main(String[] args) {
        int[] data = {5, 10, 3, 7, 8, 1, 9};
        print_data(data);
        bubble_sort(data);
        print_data(data);
    }
}

以下のコマンドでコンパイルして実行

$ javac BubbleSortTest.java
$ java BubbleSortTest

実行結果

5 10 3 7 8 1 9 3:10
   ↓ // ここは記載していないが。。。
1 3 5 7 8 9 10 
9
13
1

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
9
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?