import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;

/* <applet code="BubbleSort1.class" width="300" height="200"></applet> */

public class BubbleSort1 extends JApplet implements Runnable {
  int[] args = {10, 3, 46, 7, 23, 34, 8, 12, 4, 45, 44, 52};
  Color[] cs ={Color.RED, Color.ORANGE, Color.GREEN, Color.BLUE};
  Thread thread=null;

  @Override    
  public void start() {
    if (thread == null) {
      thread = new Thread(this);
      thread.start();
    }
  }

  @Override    
  public void stop() {
    thread = null;
  }

  @Override  
  public void paint(Graphics g) {
    int i;
    
    super.paint(g);
    for(i=0; i<args.length; i++) {
      g.setColor(cs[args[i]%cs.length]);
      g.fillRect(0, i*10, args[i]*5, 10);
    }
  }
  
  public void run() {
    Thread thisThread = Thread.currentThread();
    while(true) {
      int i, j;
      
      for (i=0; i<args.length-1; i++) {
        for (j=args.length-1; j>i && thread == thisThread; 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) {}
        }
      }
    }       
  }
}
