import java.awt.*;
import java.applet.*;
import java.util.*;

public class SortApplet extends Applet {    
    static final int N = 100;
    static final int F = 5;
    
    int a[] = new int[N];
      
    void pause(long t) { 
    	paint(getGraphics());   	
	    try { Thread.sleep(t); } catch(Exception e) {} 
    }
    
    void scramble() {
		for (int i = 0; i < a.length; i++ )
	    	a[i] = i;
	    Random rand = new Random();
		for (int i = 0; i < a.length; i++) {
	    	int j = (int) ((i+1) * rand.nextDouble());
	    	int t = a[i]; a[i] = a[j]; a[j] = t;
	    }
    }
    
    public void init() {
		resize(F*N, F*N);
		show();
		String algName = getParameter("alg");
		try {
			SortAlgorithm algorithm = (SortAlgorithm) Class.forName(algName).newInstance();
			algorithm.setParent(this);
			showStatus(algName);
			while (true) {
				pause(1000);
		    	scramble();
				algorithm.sort(a);
			} 
		}
		catch (Exception e) { 
			throw new RuntimeException("No such sort algorithm: " + algName); 
		};
    }
    
    public void paint(Graphics g) { update(g); }
    
    public void update(Graphics g) {
		g.setColor(getBackground());
	    g.fillRect(0, 0, size().height, size().height);
		g.setColor(Color.black);
		for (int i = 0, x = 0; i < N; i++, x += F)  
	    	g.fillRect(x, size().height - F*a[i], F , F);
    }
}

