Thursday, August 4, 2011

Joseph and the Amazing Technicolor Sorting Algorithm

Greek mythology has the famous tale of how Athena was birthed fully grown and armored from the head of her father Zeus. I too emerged from an epic creature, a 24 pack of diet coke armed with a basic knowledge of Java and a liking for hyperbole. Starting on my herculean quest of finding a job (who probably copied me, family killing, time traveling, son of a bitch). I started to review some textbooks as my first phone interview did not go well. Starting with the algorithm book I started by taking pseudo code (or suede-o code as some of you like to call it) from the and turn it into real code.

While it was a nice exercise it was not that fun or interesting so I attempted to attach a GUI to the code to animate sorting algorithms as they run. This did not seem like too hard of a task but after completing the GUI a number of animation bugs occurred, especially while hitting the start button twice. Researching this for a bit the Swing API has some problems with active and backgrounds thread, that take up a good deal of resources running at the same time. In this case the sorting algorithm but there is a work around called the SwingWorker class. It is strait forward to implement and using thread sleep as a timer in the JPanel can act as an animation tick using the Observable / Observer, pattern.

In the JFrame…
  public JButton createStartButton()
  {
   return new JButton(new AbstractAction("Start") 
   {
    @SuppressWarnings("rawtypes")
    public void actionPerformed(final ActionEvent the_event)
    {
     new SwingWorker()
     {
      protected Object doInBackground() throws Exception
      {
       ((VisualSortPanel) my_sort_panel).start();
       return null;
      }
     }.execute();
    } 
   }); 
  }
In the JPanel…
 public void update(final Observable the_observable, final Object the_object)
 { 
  try 
  {
   if(my_sort.getClass().getName().contains("BubbleSort"))
   {
    Thread.sleep(ANIMATION_DELAY / 10);
   }
   else
   {
    Thread.sleep(ANIMATION_DELAY);
   }  
  }
  catch (final InterruptedException the_exception) 
  {
   the_exception.printStackTrace();
  }
 
  repaint();
 }
Now that the animation was working it was getting a little tedious adding each sort to a list to be added to a Combo Box to be selected. There actually is a Java feature built in that allows dynamic loading of classes. More so there is also a way to dynamically compile files too so within a program you can write, compile, and execute classes on the fly. Back to dynamic loading, the class is called ClassLoader and accepts *.class files. The trick is reading the API is the class file must be given in something called its “binary name” which just means its package location not its directory path on your disk. So this takes a bit of leg work of searching the bin directory for files you want, get their names, and then append them to a String with the package directory.

Like most things in Java you can be lazy if you want to spend a second Googling it.

   final File[] files = new File("bin\\sort").listFiles(new FilenameFilter()
   {
    public boolean accept(final File directory, final String name)
    {
     return !name.contains("Abstract") && name.endsWith(".class");
    }
   });
Is all you need to build an array with each class file and can be filtered by changing the return on the overridden method.

Loading the classes after finding them is a little more tricky.

   for(File file : files)
   {
    final String path = file.getName().substring(0, file.getName().indexOf("."));
     try
     {
      Class<?> load_class = ClassLoader.getSystemClassLoader().loadClass("sort." + path);
     } 
     catch (final Exception the_exception)
     {
      the_exception.printStackTrace();
     }
   }
This will iterate through the file array and will load each class. However this does not instantiate the object but can be done with an additional line of code.

       sort_list.add((AbstractSort) load_class.getConstructor().newInstance());  
In this line both the “getConstructor()” and “newInstance()” also take any arguments the construct of the class also takes.

The end result is this amazing program that will soon be the twelfth wonder of the world.


The code for the program can be downloaded here.