tanakahdaのプログラマ手帳

プログラミングとかソフトウェア開発とかの備忘録

バブルソートの実装@Java

package examples;

import java.util.Arrays;

public class BubbleSort {

	public static void main(String[] args) {

		int[] score = {98, 23, 32, 63, 55};

		// 一番最後の要素は左右の比較が不要なので「-1」する
		final int COMPARE_COUNT = score.length - 1;

		int temp = 0;

		for (int x = 0; x < COMPARE_COUNT; x++) {
			for (int y = 0; y < (COMPARE_COUNT - x); y++) {
				// 左右の要素を比較して、大きい値を左に入れ替える
				if (score[y] < score[y + 1]) {
					temp = score[y];
					score[y] = score[y + 1];
					score[y + 1] = temp;
				}
				System.out.println(Arrays.toString(score));
			}
		}
//		System.out.println(Arrays.toString(score));
	}

}