// とりあえずバブルソート

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/*
<applet code="BubbleSort2.class" width="300" height="200">
</applet>
*/

public class BubbleSort2 extends JApplet implements Runnable, ActionListener {
  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;
  private boolean threadSuspended=true;

  @Override
  public void init() {
    JButton step = new JButton("Step");
    step.addActionListener(this);
    setLayout(new FlowLayout());
    add(step);
  }

  @Override
  public void start() {
    if (thread == null) {
      thread = new Thread(this);
      thread.start();
    }
  }

  @Override
  public void stop() {
    thread = null;
  }

  public synchronized void actionPerformed(ActionEvent e) {
    threadSuspended=false;
    notify();
  }

  @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() {
    while(true) {
      int i, j;
      
      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();
          /* repaintの後で止まる */
	  try {
            synchronized(this) { 
               while (threadSuspended) {
                  wait();
               }
               threadSuspended=true;
            }
          } catch (InterruptedException e) {}
	}
      }
    }
  }
}
