講師の方の見本でソースコードの結果と図解の説明が一致してるように思えず混乱中。
package trainig04; import java.util.ArrayList; import java.util.List; /* * バブルソート(基本選択法)のサンプル */ public class BubbleSort { public static void main(String[] args) { // 配列の生成 int[] array = { 55, 12, 81, 2, 99, 69, 22 }; // 要素数「7」の配列 // バブルソート for (int i = 0; i < array.length - 1; i++) { // 7 -1 = 6 なので i = 0~5までループ for(int before = 0; before < array.length; before++) { System.out.print(array[before]); if(before != array.length -1) { System.out.print(", "); } } System.out.println("\n◇" + i + "周目【i = " + i + "】"); for (int j = array.length - 1; j > i; j--) { // 7 -1 = 6 なので j = 6~(i + 1)までループ if (array[ j - 1 ] > array[ j ]) { // もし1つ前の要素の方が大ききれば入替える int tmpNum = array[ j - 1 ]; array[ j - 1 ] = array[ j ]; array[ j ] = tmpNum; } // 途中の配列の状態 for(int after = 0; after < array.length; after++) { System.out.print(array[after]); if(after != array.length -1) { System.out.print(", " ); } } System.out.println(" 【j = " + j + "】"); } System.out.println(); System.out.println("==========================="); System.out.println(); } // 表示 System.out.println("最終的なソートの結果"); for (int i : array) { System.out.print(i + ", "); } } }
バブルソート(図解)
ソースコードの結果
55, 12, 81, 2, 99, 69, 22 ◇0周目【i = 0】 55, 12, 81, 2, 99, 22, 69 【j = 6】 55, 12, 81, 2, 22, 99, 69 【j = 5】 55, 12, 81, 2, 22, 99, 69 【j = 4】 55, 12, 2, 81, 22, 99, 69 【j = 3】 55, 2, 12, 81, 22, 99, 69 【j = 2】 2, 55, 12, 81, 22, 99, 69 【j = 1】 =========================== 2, 55, 12, 81, 22, 99, 69 ◇1周目【i = 1】 2, 55, 12, 81, 22, 69, 99 【j = 6】 2, 55, 12, 81, 22, 69, 99 【j = 5】 2, 55, 12, 22, 81, 69, 99 【j = 4】 2, 55, 12, 22, 81, 69, 99 【j = 3】 2, 12, 55, 22, 81, 69, 99 【j = 2】 =========================== 2, 12, 55, 22, 81, 69, 99 ◇2周目【i = 2】 2, 12, 55, 22, 81, 69, 99 【j = 6】 2, 12, 55, 22, 69, 81, 99 【j = 5】 2, 12, 55, 22, 69, 81, 99 【j = 4】 2, 12, 22, 55, 69, 81, 99 【j = 3】 =========================== 2, 12, 22, 55, 69, 81, 99 ◇3周目【i = 3】 2, 12, 22, 55, 69, 81, 99 【j = 6】 2, 12, 22, 55, 69, 81, 99 【j = 5】 2, 12, 22, 55, 69, 81, 99 【j = 4】 =========================== 2, 12, 22, 55, 69, 81, 99 ◇4周目【i = 4】 2, 12, 22, 55, 69, 81, 99 【j = 6】 2, 12, 22, 55, 69, 81, 99 【j = 5】 =========================== 2, 12, 22, 55, 69, 81, 99 ◇5周目【i = 5】 2, 12, 22, 55, 69, 81, 99 【j = 6】 =========================== 最終的な表示 2, 12, 22, 55, 69, 81, 99,
う~ん、何時間考えてもソースコードと図解の流れの関係性が理解できない。
ソースコードだと内側のループは、配列の最後の要素から順に比較しているように思えるんですが、図解だと配列の先頭から比較してるようになっている気が...。
明日、講師の人に聞いてみよう。ソートは難しいですね。
2017年6月27日 追記
図解の訂正版をいただきました。