import java.awt.*;
import javax.swing.*;

public class BubbleSort1 extends JPanel implements Runnable {
	private int[] init = {10, 52, 23, 34, 8, 12, 4, 46, 7, 45, 44, 3};
	private int[] args = new int[init.length];
	private final Color[] cs = {Color.RED, Color.ORANGE, Color.GREEN, Color.BLUE};
	private volatile Thread thread = null;
	private int i, j;

	public BubbleSort1() {
		setPreferredSize(new Dimension(320, 250));
		startThread();
	}

	private void startThread() {
		if (thread == null) {
			thread = new Thread(this);
			thread.start();
		}
	}

	@Override
	public void paintComponent(Graphics g) {
		int k;
		super.paintComponent(g);
		g.setColor(Color.YELLOW);
		g.fillOval(5, 50 + j * 10, 10, 10);
		g.setColor(Color.CYAN);
		g.fillOval(5, 50 + i * 10, 10, 10);
		for (k = 0; k < args.length; k++) {
			g.setColor(cs[k % cs.length]);
			g.fillRect(20, 50 + k * 10, args[k] * 5, 10);
		}
	}

	public void run() {
		while (true) {
			for (int k = 0; k < init.length; k++) { args[k] = init[k]; }
			// バブルソートアルゴリズム
			for (i = 0; i < args.length - 1; i++) {
				for (j = args.length - 1; j > i; j--) {
					if (args[j - 1] > args[j]) { // スワップする。
						int tmp = args[j - 1];
						args[j - 1] = args[j];
						args[j] = tmp;
						repaint();
						try { // repaintの後でしばらく止まる
							Thread.sleep(500);
						} catch (InterruptedException e) {}
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(() -> {
			JFrame frame = new JFrame("バブルソート");
			frame.add(new BubbleSort1());
			frame.pack();
			frame.setVisible(true);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		});
	}
}
