# Animating Graphical Sort

• March 15th, 2013, 10:39 AM
SiL3NTK0D3R
Animating Graphical Sort
I am working on an assignment called "Graphical Sort", which is basically animating sort algorithm graphically.

I just need help on animating the sorting process.

I tried using Thread, but the program hangs till the threading process is completed, then it shows the final result.

Below are the picture of how my program looks like:
Attachment 1870
Attachment 1871

Below is the JPanel class I made, which I paint on:
Code :

```import javax.swing.*; import java.awt.*; import java.util.*;   public class PaintPanel extends JPanel { // Create an array of 34 element size int[] Arr = new int [34]; // Set default X pointer to 20 int x = 50; // Declare Y pointer to 660 int y = 660; // Set the length of array to n variable int n = Arr.length;     /* * main method * @param none * @return none */ public PaintPanel () { randomNums (); revalidate (); repaint (0, 150, 800, 700); }     /* * Generates random numbers between 50 and 750 and stores it into the Arr variable * @param none * @return none */ public void randomNums () { // call randomGenerator object Random randomGenerator = new Random (); // Loop 33 times = Generates 33 random integers for (int i = 0 ; i <= 33 ; ++i) { // Generate random Number int randomInt = randomGenerator.nextInt (700); // Conditional statement, if any number is less than 50, then discard it and generate new number if (randomInt > 50) // Assign each random number into Arr Element Arr [i] = randomInt; else { // Regenerate Random Number randomInt = randomGenerator.nextInt (700); // Assign it again Arr [i] = randomInt; } } }     /* * Bubble Sort Algorithm * @param none * @return none */ public void bubble () { //Pre: a is an array with values. It is of size n //Post: the values in a are put in ascending order int temp; //int a[] = Arr; for (int i = 0 ; i < n - 1 ; i++) { for (int j = 0 ; j < n - 1 - i ; j++) { // compare the two neighbours if (Arr [j + 1] < Arr [j]) { //swap the neighbours if necessary temp = Arr [j]; Arr [j] = Arr [j + 1]; Arr [j + 1] = temp; repaint (0, 150, 800, 700); } } } }     /* * Paints 33 rectangle Strips to the screen * @param Graphics g * @return none */ public void paintComponent (Graphics g) { super.paintComponent (g); // Call Graphics2D Object Graphics2D g2 = (Graphics2D) g.create (); // Create Paint Object with gradient Fill Paint p = new GradientPaint ( 0, 0, new Color (0x44A2FF), getWidth (), 0, new Color (0x0CBEAE), true ); // Set the gradient fill to the Graphics2D Object g2.setPaint (p);   // Loop through the Array and display series of Rectangular Strips for (int i = 0 ; i < Arr.length ; ++i) { // Fill out the Rectangle g2.fillRect (x, y, Arr [i], 8); y = y - 15; } g2.dispose (); } }```

What should I use to animate the process. I also want to show which rectangular strips are being compared during the process of sorting.

Thank You
• March 15th, 2013, 10:47 AM
SiL3NTK0D3R
Animating Graphical Sort
I am working on an assignment called "Graphical Sort", which is basically animating sort algorithm graphically.

I just need help on animating the sorting process.

I tried using Thread, but the program hangs till the threading process is completed, then it shows the final result.

Below are the picture of how my program looks like:
Attachment 1870
Attachment 1871

Below is the JPanel class I made, which I paint on:
Code :

```import javax.swing.*; import java.awt.*; import java.util.*;   public class PaintPanel extends JPanel { // Create an array of 34 element size int[] Arr = new int [34]; // Set default X pointer to 20 int x = 50; // Declare Y pointer to 660 int y = 660; // Set the length of array to n variable int n = Arr.length;     /* * main method * @param none * @return none */ public PaintPanel () { randomNums (); revalidate (); repaint (0, 150, 800, 700); }     /* * Generates random numbers between 50 and 750 and stores it into the Arr variable * @param none * @return none */ public void randomNums () { // call randomGenerator object Random randomGenerator = new Random (); // Loop 33 times = Generates 33 random integers for (int i = 0 ; i <= 33 ; ++i) { // Generate random Number int randomInt = randomGenerator.nextInt (700); // Conditional statement, if any number is less than 50, then discard it and generate new number if (randomInt > 50) // Assign each random number into Arr Element Arr [i] = randomInt; else { // Regenerate Random Number randomInt = randomGenerator.nextInt (700); // Assign it again Arr [i] = randomInt; } } }     /* * Bubble Sort Algorithm * @param none * @return none */ public void bubble () { //Pre: a is an array with values. It is of size n //Post: the values in a are put in ascending order int temp; //int a[] = Arr; for (int i = 0 ; i < n - 1 ; i++) { for (int j = 0 ; j < n - 1 - i ; j++) { // compare the two neighbours if (Arr [j + 1] < Arr [j]) { //swap the neighbours if necessary temp = Arr [j]; Arr [j] = Arr [j + 1]; Arr [j + 1] = temp; repaint (0, 150, 800, 700); } } } }     /* * Paints 33 rectangle Strips to the screen * @param Graphics g * @return none */ public void paintComponent (Graphics g) { super.paintComponent (g); // Call Graphics2D Object Graphics2D g2 = (Graphics2D) g.create (); // Create Paint Object with gradient Fill Paint p = new GradientPaint ( 0, 0, new Color (0x44A2FF), getWidth (), 0, new Color (0x0CBEAE), true ); // Set the gradient fill to the Graphics2D Object g2.setPaint (p);   // Loop through the Array and display series of Rectangular Strips for (int i = 0 ; i < Arr.length ; ++i) { // Fill out the Rectangle g2.fillRect (x, y, Arr [i], 8); y = y - 15; } g2.dispose (); } }```

What should I use to animate the process. I also want to show which rectangular strips are being compared during the process of sorting.

Thank You
• March 15th, 2013, 12:00 PM
Norm
Re: Animating Graphical Sort
Normally with animation the program makes a change, calls repaint() and the painting method is called to display that change. Then another change is made, repaint() is called etc

How is the posted code executed for testing? There is not a main() method.
• March 17th, 2013, 08:38 AM
SiL3NTK0D3R
Re: Animating Graphical Sort
I figured it out, I had to completely remake the program using Thread in different class.
Below are the codes for fully working program, but I need to show which 2 bars are being compared and then swapped.

Code :

```// Import all required Libraries // Swing, Paint, Events, Randomizer, etc.. import java.awt.*; import java.awt.EventQueue; import java.awt.event.*; import java.util.Random; import javax.swing.*;     public class MainFrame extends JFrame implements ActionListener { // Instance Varaible, Global at this point // Declare all the Buttons and set text in it public static JButton Randomize = new JButton ("RANDOMIZE"); public static JButton BubbleSort = new JButton ("Bubble Sort"); public static JButton SelectionSort = new JButton ("Selection Sort"); public static JButton InsertionSort = new JButton ("Insertion Sort"); public static JButton ShakerSort = new JButton ("Shaker Sort"); // Declare new JFrame called mainFrame JFrame mainFrame; // Make new TextArea and we will call it InfoArea public static JTextArea InfoArea = new JTextArea (); // Declare Array, which will hold all the randomzied numbers static int Array[]; // Call out the Sorts Class, which contains JPanel Class Sorts sorts;   /* * @method GenerateRandomNums * @desc This method will create 40 random numbers, starting from 50 to 750 * @params none required * @returns none */ public void GenerateRandomNums () { // new the Array variable Array = new int [40]; // call randomGenerator object Random randomGenerator = new Random (); // Loop 33 times = Generates 33 random integers for (int i = 0 ; i <= 39 ; ++i) { // Generate random Number int randomInt = randomGenerator.nextInt (550); // Conditional statement, if any number is less than 50, then discard it   and generate new number if (randomInt > 50) // Assign each random number into Arr Element Array [i] = randomInt; else { // Regenerate Random Number randomInt = randomGenerator.nextInt (700); // Assign it again Array [i] = randomInt; } } }   /* * @method DisplayMF * @desc This method hold the swing component of the program, displays the   controls * @params none required * @returns none */ public void DisplayMF () { // Mutate MainFrame Variable, set its properties mainFrame = new JFrame ("Graphical Sorting by Priyank Patel"); mainFrame.setSize (820, 800); mainFrame.setLocation (100, 100); mainFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); mainFrame.setResizable (false); mainFrame.setDefaultLookAndFeelDecorated(true); mainFrame.setBackground(Color.white);   // Mutate Randomize Variable, set its properties Randomize.setSize (120, 25); Randomize.setLocation (50, 15); Randomize.addActionListener (this); mainFrame.getContentPane ().add (Randomize);   // Mutate BubbleSort Variable, set its properties BubbleSort.setSize (100, 25); BubbleSort.setLocation (200, 15); BubbleSort.addActionListener (this); BubbleSort.setEnabled (false); mainFrame.getContentPane ().add (BubbleSort);   // Mutate SelectionSort Variable, set its properties SelectionSort.setSize (120, 25); SelectionSort.setLocation (330, 15); SelectionSort.addActionListener (this); SelectionSort.setEnabled (false); mainFrame.getContentPane ().add (SelectionSort);   // Mutate InsertionSort Variable, set its properties InsertionSort.setSize (120, 25); InsertionSort.setLocation (480, 15); InsertionSort.addActionListener (this); InsertionSort.setEnabled (false); mainFrame.getContentPane ().add (InsertionSort);   // Mutate ShakerSort Variable, set its properties ShakerSort.setSize (120, 25); ShakerSort.setLocation (630, 15); ShakerSort.addActionListener (this); ShakerSort.setEnabled (false); mainFrame.getContentPane ().add (ShakerSort);   // Mutate InfoArea Variable, set its properties InfoArea.setSize (700, 100); InfoArea.setLocation (50, 50); InfoArea.setEditable (false); mainFrame.getContentPane ().add (InfoArea);   // Mutate Sorts Variable, set its properties sorts = new Sorts (40); sorts.setBackground(Color.white); mainFrame.getContentPane ().add (sorts);   // Display the Frame when it's called out mainFrame.show (); }   /* * @method actionPerformed * @desc This method controls all the actions that are being called out * @params none required * @returns none */ public void actionPerformed (ActionEvent e) { if (e.getSource () == Randomize) { InfoArea.setText ("");   GenerateRandomNums (); sorts.assignArrayElements (Array); sorts.repaint (0, 200, 800, 600);   BubbleSort.setEnabled (true); InsertionSort.setEnabled (true); SelectionSort.setEnabled (true); ShakerSort.setEnabled (true); } else if (e.getSource () == BubbleSort) { Randomize.setEnabled (false); InsertionSort.setEnabled (false); SelectionSort.setEnabled (false); ShakerSort.setEnabled (false);   InfoArea.setText ("Bubble Sort is a fairly slow sort that in its average   and worst case, is O(n^2)."); InfoArea.append ("\nHowever in its best case, it is close to O(n)."); InfoArea.append ("\nIn Bubble sort, each element slowly \"bubbles\"   towards its place.");   sorts.type = 1; sorts.thread = new Thread (sorts); sorts.thread.start (); } else if (e.getSource () == InsertionSort) { Randomize.setEnabled (false); BubbleSort.setEnabled (false); InsertionSort.setEnabled (true); SelectionSort.setEnabled (false); ShakerSort.setEnabled (false);   InfoArea.setText ("Insertion Sort is a sort that in its best, average and   worst case, is O(n^2)."); InfoArea.append ("\nIn Insertion Sort, each element is placed in a sorted   section of the array in the correct position.");   sorts.type = 2; sorts.thread = new Thread (sorts); sorts.thread.start (); } else if (e.getSource () == SelectionSort) { Randomize.setEnabled (false); BubbleSort.setEnabled (false); InsertionSort.setEnabled (false); SelectionSort.setEnabled (true); ShakerSort.setEnabled (false);   InfoArea.setText ("\"Selection Sort is a sort that in its best, average   and worst case, is O(n^2)."); InfoArea.append ("\nIn Selection Sort, the largest number in the array is   swapped into the place. Then the next largest number is swapped into place.");   sorts.type = 3; sorts.thread = new Thread (sorts); sorts.thread.start (); } else if (e.getSource () == ShakerSort) { Randomize.setEnabled (false); BubbleSort.setEnabled (false); InsertionSort.setEnabled (false); SelectionSort.setEnabled (false); ShakerSort.setEnabled (true);   InfoArea.setText ("Shaker Sort is a sort that in its average and worst   case, is O(n^2). It is close to O(n) when the array is almost sorted."); InfoArea.append ("\nIn Shaker Sort, elements are compared with the next   in alternating directions.");   sorts.type = 4; sorts.thread = new Thread (sorts); sorts.thread.start (); } }   /* * @method main * @desc This is the main method, without it the program will not run * @params array of arguments * @returns none */ public static void main (String[] args) { // Invoke EventQueue EventQueue.invokeLater (new Runnable () { public void run () { // Call out the MainFrame MainFrame MF = new MainFrame (); // Call out the DisplayMF method of MainFrame MF.DisplayMF (); } } ); } }```

Code :

```import javax.swing.*; import java.awt.*; import java.awt.event.*;   /** * * @author Home */ abstract class Sorting extends JPanel implements Runnable {     int TempArr[]; Thread thread;   public Sorting (int len) { this.setPreferredSize (new Dimension (800, 600)); this.setLocation (0, 200);   thread = new Thread (this); TempArr = new int [len]; for (int i = 0 ; i < len ; i++) TempArr [i] = 0; }     public void assignArrayElements (int a[]) { for (int i = 0 ; i < a.length ; i++) TempArr [i] = a [i]; }     public void paint (Graphics g) { super.paint (g); // Call Graphics2D Object Graphics2D g2 = (Graphics2D) g.create (); // Create Paint Object with gradient Fill Paint p = new GradientPaint ( 0, 0, new Color (0x44A2FF), getWidth (), 0, new Color (0x0CBEAE), true ); // Set the gradient fill to the Graphics2D Object g2.setPaint (p);     for (int i = 1 ; i < TempArr.length ; i++) { g2.fillRect ((19 * i) + 8, 760 - TempArr [i], 10, TempArr [i]); }   g2.dispose (); }     public void Animate () { repaint (0, 200, 800, 600);   try { Thread.sleep (50); } catch (Exception ex) {   } thread.yield (); }     abstract public void sort ();   public void run () { sort (); } }```

Code :

```/* * To change this template, choose Tools | Templates * and open the template in the editor. */   /** * * @author Home */ public class Sorts extends Sorting {   int type;   public Sorts (int len) { super (len); }     public void sort () { long startTime, endTime; int temp;   switch (type) { case 1: // bubble startTime = System.currentTimeMillis ();   for (int i = 0 ; i < TempArr.length - 1 ; i++) { for (int j = 0 ; j < TempArr.length - 1 - i ; j++) { if (TempArr [j + 1] < TempArr [j]) { temp = TempArr [j]; TempArr [j] = TempArr [j + 1]; TempArr [j + 1] = temp; Animate (); } } }   endTime = System.currentTimeMillis ();   MainFrame.InfoArea.append ("\nCompleted Task in: " + (endTime - startTime));   MainFrame.Randomize.setEnabled (true); MainFrame.BubbleSort.setEnabled (true); MainFrame.InsertionSort.setEnabled (false); MainFrame.SelectionSort.setEnabled (false); MainFrame.ShakerSort.setEnabled (false);   thread.stop (); break;   case 2: // insertion startTime = System.currentTimeMillis ();   int numSorted = 1; int index; while (numSorted < TempArr.length) { //take the first unsorted value temp = TempArr [numSorted]; //.. and insert it among the sorted: for (index = numSorted ; index > 0 ; index--) { if (temp < TempArr [index - 1]) { TempArr [index] = TempArr [index - 1]; } else { break; } }   //re-insert value TempArr [index] = temp; Animate (); numSorted++; }   endTime = System.currentTimeMillis ();   MainFrame.InfoArea.append ("\nCompleted Task in: " + (endTime - startTime));   MainFrame.Randomize.setEnabled (true); MainFrame.BubbleSort.setEnabled (false); MainFrame.InsertionSort.setEnabled (true); MainFrame.SelectionSort.setEnabled (false); MainFrame.ShakerSort.setEnabled (false);   thread.stop (); break;   case 3: // selection startTime = System.currentTimeMillis ();   int numUnsorted = TempArr.length; int max; //index of largest value while (numUnsorted > 0) { //determine maximum value in array max = 0; for (index = 1 ; index < numUnsorted ; index++) { if (TempArr [max] < TempArr [index]) max = index; }     temp = TempArr [max]; TempArr [max] = TempArr [numUnsorted - 1]; TempArr [numUnsorted - 1] = temp; numUnsorted--; Animate (); }   endTime = System.currentTimeMillis ();   MainFrame.InfoArea.append ("\nCompleted Task in: " + (endTime - startTime));   MainFrame.Randomize.setEnabled (true); MainFrame.BubbleSort.setEnabled (false); MainFrame.InsertionSort.setEnabled (false); MainFrame.SelectionSort.setEnabled (true); MainFrame.ShakerSort.setEnabled (false);   thread.stop (); break;   case 4: // shaker startTime = System.currentTimeMillis ();   int j; int limit = TempArr.length; //last element in the array int st = -1; //starting element in the array char swap = 't'; //keeps track of swaps so we can stop early while (st < limit && swap == 't') { swap = 'f'; st++; limit--; //forward pass of array for (j = st ; j < limit - 1 ; j++) { if (TempArr [j] > TempArr [j + 1]) { int T = TempArr [j]; TempArr [j] = TempArr [j + 1]; TempArr [j + 1] = T; swap = 't'; //print array to see what this pass looks like Animate (); } }     //backward pass of the array for (j = limit - 1 ; j >= st ; j--) { if (TempArr [j] > TempArr [j + 1]) { int T = TempArr [j]; TempArr [j] = TempArr [j + 1]; TempArr [j + 1] = T; swap = 't'; //print array to see what this pass looks like Animate (); } } }     endTime = System.currentTimeMillis ();   MainFrame.InfoArea.append ("\nCompleted Task in: " + (endTime - startTime));   MainFrame.Randomize.setEnabled (true); MainFrame.BubbleSort.setEnabled (false); MainFrame.InsertionSort.setEnabled (false); MainFrame.SelectionSort.setEnabled (false); MainFrame.ShakerSort.setEnabled (true);   thread.stop (); break; } } }```

So, how can I display which 2 bars are being compared and swapped?

Thanks