2014年2月10日月曜日

バブルソートの実装

隣り合う要素通しを比較して大小の関係が正しくない場合に交換するという操作を各要素について繰り返すことで整列させるアルゴリズムです。

ソースコード

public class Test {
    public static void main(String[] args) {
       int[] a = new int[]{3,2,5,4,1};
       dumpArray(a);
       for ( int i = 0; i < a.length - 1; i++ ) {
           for ( int j = 1; j < a.length; j++ ) {
               if ( a[j - 1] > a[j] ) {
                   int tmp = a[j - 1];
                   a[j - 1] = a[j];
                   a[j] =tmp;
               }
           }
           dumpArray(a);
       }
    }
    // 配列の内容を表示します
    private static void dumpArray(int[] a) {
        for ( int n : a ) {
            System.out.print(n + " ");
        }
        System.out.println();
    }
}

出力

3 2 5 4 1 
2 3 4 1 5 
2 3 1 4 5 
2 1 3 4 5 
1 2 3 4 5