Advertisement
ffpaladin

Animating the Sorted Rectangles (quick coded solution)

Jul 19th, 2013
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. // By: Sherol Chen
  2. // Animating the Sorted Rectangles
  3.    
  4. import acm.graphics.*;
  5. import acm.program.*;
  6.  
  7. public class MyVisualSort extends GraphicsProgram{
  8.        
  9.     private int[] array = {23, 42, 55, 64, 70, 10, 33, 44, 20};
  10.    
  11.     public static void main(String[] args) {
  12.         new myvisualsort().start(args);
  13.     }
  14.    
  15.     public void run() {
  16.             while(true)
  17.             {    
  18.                 for (int i=0; i<array.length; i++)
  19.                     for (int j=i; j<array.length-1; j++)
  20.  
  21.                         if ( array[j] > array[j+1])
  22.                         {
  23.                             swap(array, j, j+1);    // generic swap function
  24.                             updateGraphics(array);   // however you drew it
  25.                         }
  26.              }
  27.     }
  28.    
  29.     // Good old swap function
  30.     private void swap (int[] a, int x, int y)
  31.     {
  32.         int poopstall = a[x];
  33.         a[x] = a[y];
  34.         a[y] = poopstall;
  35.     }
  36.    
  37.     private void updateGraphics(int[] a)
  38.     {
  39.                 removeAll();            // clear canvas
  40.         for (int i=0; i<a.length; i++)
  41.         {
  42.             // just doing basic scaling of the data
  43.             GRect rect = new GRect(i*50 + 200, 0, 10, a[i]*5);
  44.             add(rect);
  45.         }
  46.         pause(200);
  47.     }
  48.    
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement