Source of Sort2.java


  1: import java.awt.*;
  2: 
  3: public class Sort2 extends AlgorithmAnimator {
  4:   public void initAnimator() {
  5:     setDelay(20); 
  6:     algName = "BubbleSort"; 
  7:     String at = getParameter("alg");
  8:     if (at != null)
  9:       algName = at; 
 10:     algorithmFactory = new StaticAlgoFactory(this);  
 11:     theAlgorithm = algorithmFactory.makeSortAlgorithm(algName); 
 12:     scramble();  
 13:   }
 14: 
 15:   protected void algorithm() {
 16:     if (theAlgorithm != null)
 17:       theAlgorithm.sort(arr);
 18:   }
 19: 
 20:   protected void scramble() {
 21:     arr = new int[getSize().height / 2];
 22:     for (int i = arr.length; --i >= 0;) {
 23:       arr[i] = i;
 24:     }
 25:     for (int i = arr.length; --i >= 0;) {
 26:       int j = (int)(i * Math.random());
 27:       SortAlgorithm.swap(arr, i, j); 
 28:     }
 29:   }
 30: 
 31:   protected void paintFrame(Graphics g) {
 32:     Dimension d = getSize(); 
 33:     g.setColor(Color.white);
 34:     g.fillRect(0, 0, d.width, d.height); 
 35:     g.setColor(Color.black);
 36:     int y = d.height - 1;    
 37:     double f = d.width / (double) arr.length;
 38:     for (int i = arr.length; --i >= 0; y -= 2) 
 39:       g.drawLine(0, y, (int)(arr[i] * f), y);
 40:   }
 41: 
 42:   protected int    arr[]; 
 43:   protected String algName; 
 44: 
 45:   protected SortAlgorithm        theAlgorithm;
 46:   protected SortAlgorithmFactory algorithmFactory;    
 47: }