This is an animation of the bubble sort algorithm. The random positive numbers to be sorted are represented by red outline circles whose distance from the bottom of the animation frame is proportional to their magnitude. Each circle is ``bubbled'' up to where it belongs in the sorted array by comparing it to the circles on its right. The current circle is changed to solid blue. Each pair of circles being compared is connected briefly by a green line. If the circle on the right is smaller, the connecting line is changed to red and the two circles swap positions. Each circle changes to solid black when it moves into its final sorted position.

private static void bubbleSort(int[] a) { // into non-decreasing order
   for (int i = a.length - 1; i >= 0; i--) {
      for (int j = 0; j < i; j++) {
         xa.color("C"+j, Color.blue);     // make candidate to
         xa.fill("C"+j, xa.SOLID);        // bubble solid blue
         xa.delay(1);
         // momentarily connect the two icons compared with a line
         xa.pointLine("temp", scaleX(j), scaleY(a[j]), scaleX(j+1),
            scaleY(a[j+1]), Color.green, xa.THICK);
         xa.delay(1);
         if (a[j] > a[j+1]) {             // swap the icon locations
            xa.color("temp", Color.red);
            xa.delay(1);
            xa.moveAsync("C"+j, scaleX(j+1), scaleY(a[j]));
            xa.move("C"+(j+1), scaleX(j), scaleY(a[j+1]));
            xa.swapIds("C"+j, "C"+(j+1)); // swap ids of the icons
            int temp = a[j+1]; a[j+1] = a[j]; a[j] = temp;
         } else {
            xa.fill("C"+j, xa.OUTLINE);   // make the smaller icon ...
            xa.color("C"+j, Color.red);      // ... outline red ...
            xa.delay(1);
            xa.color("C"+(j+1), Color.blue); // ... and the larger ...
            xa.fill("C"+(j+1), xa.SOLID);    // ... solid blue
            xa.delay(1);
         }
         xa.delete("temp");
      }
      // color the icon black to indicate it is in final position
      xa.color("C"+i, Color.black);
      xa.delay(1);
   }
   xa.fill("C0", xa.SOLID);
   xa.delay(1);
}
At the bottom of the animation window is a button and text field showing the default values of some of the command line arguments. Alter these as needed and click the button. To start the animation, push the ``Start'' button after checking the command line arguments text field and clicking that button. Check the browser's Java console for error messages. An applet appears here if you have a Java-enabled browser.


© 1998 Stephen J. Hartley