Java Program to Create Applet to Simulate Any Sorting Technique

This is a java program to create an applet to simulate a sorting technique. This applet demonstrates Bubble Sort.

Here is the source code of the Create Java Applet to Simulate Any Sorting Technique. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. package com.sanfoundry.combinatorial;
  2.  
  3. import java.applet.Applet;
  4. import java.awt.BorderLayout;
  5. import java.awt.Button;
  6. import java.awt.Canvas;
  7. import java.awt.Choice;
  8. import java.awt.Color;
  9. import java.awt.Dimension;
  10. import java.awt.Event;
  11. import java.awt.FlowLayout;
  12. import java.awt.Font;
  13. import java.awt.FontMetrics;
  14. import java.awt.Graphics;
  15. import java.awt.Image;
  16. import java.awt.Panel;
  17. import java.awt.Point;
  18.  
  19. @SuppressWarnings("deprecation")
  20. class ExplainBox extends Canvas
  21. {
  22.     private static final long serialVersionUID = 1L;
  23.     static final int marginX = 6;
  24.     static final int marginY = 3;
  25.     String text = "";
  26.  
  27.     public ExplainBox()
  28.     {
  29.         setFont(new Font("TimesRoman", Font.PLAIN, 12));
  30.     }
  31.  
  32.     public void setText(String text)
  33.     {
  34.         this.text = text;
  35.         invalidate();
  36.     }
  37.  
  38.     public void validate()
  39.     {
  40.         FontMetrics metrics = getFontMetrics(getFont());
  41.         int baseLine = metrics.getAscent();
  42.         int lineHeight = baseLine + metrics.getDescent();
  43.         int width = metrics.stringWidth(text);
  44.         Point corner = location();
  45.         reshape(corner.x, corner.y, width + 2 * marginX, lineHeight + 2
  46.                 * marginY);
  47.     }
  48.  
  49.     public void paint(Graphics g)
  50.     {
  51.         g.setColor(Color.black);
  52.         Dimension size = size();
  53.         g.drawRect(0, 0, size.width - 1, size.height - 1);
  54.         FontMetrics metrics = getFontMetrics(getFont());
  55.         g.drawString(text, marginX, marginY + metrics.getAscent());
  56.     }
  57.  
  58.     public boolean mouseExit(Event event, int x, int y)
  59.     {
  60.         return true;
  61.     }
  62. }
  63.  
  64. @SuppressWarnings("deprecation")
  65. class CodePanel extends Panel
  66. {
  67.     private static final long serialVersionUID = 1L;
  68.     static final int marginX = 15;
  69.     static final int marginY = 20;
  70.     static final int offsetX = 1;
  71.     static final int offsetY = 1;
  72.     static final int none = -1;
  73.     String code[]; // Array to hold the source code
  74.     String explainations[]; // Array to hold the explaination of source code
  75.     Font font = new Font("TimesRoman", Font.PLAIN, 16);
  76.     int lineHeight;
  77.     int baseLine;
  78.     int maxWidth = 0;
  79.     int highlightedLine = none;
  80.     ExplainBox explaination = new ExplainBox();
  81.     Applet applet;
  82.  
  83.     public CodePanel(String code[], String explainations[], Applet applet)
  84.     {
  85.         this.code = code;
  86.         this.explainations = explainations;
  87.         this.applet = applet;
  88.         setBackground(Color.white); // Set the background of code panel to be
  89.                                     // white
  90.         explaination.setBackground(Color.lightGray);
  91.         explaination.setForeground(Color.lightGray);
  92.         add(explaination);
  93.         explaination.hide(); // Hide explaination until the code line is clicked
  94.     }
  95.  
  96.     public Dimension preferredSize()
  97.     {
  98.         return new Dimension(280, 300);
  99.     }
  100.  
  101.     public void addNotify()
  102.     {
  103.         super.addNotify();
  104.         setFont(font);
  105.         FontMetrics metrics = getFontMetrics(font);
  106.         baseLine = metrics.getAscent();
  107.         lineHeight = baseLine + metrics.getDescent();
  108.         for (int i = 0; i < code.length; i++)
  109.         {
  110.             maxWidth = Math.max(maxWidth, metrics.stringWidth(code[i]));
  111.         }
  112.     }
  113.  
  114.     public void paint(Graphics g)
  115.     {
  116.         int y = marginY + baseLine;
  117.         for (int i = 0; i < code.length; i++, y += lineHeight)
  118.         {
  119.             setBackground(Color.white);
  120.             g.drawString(code[i], marginX, y);
  121.         }
  122.         highlightLine(highlightedLine);
  123.     }
  124.  
  125.     public void reset()
  126.     {
  127.         if (highlightedLine != none)
  128.         {
  129.             colorLine(highlightedLine, Color.white);
  130.         }
  131.         highlightedLine = none;
  132.     }
  133.  
  134.     public void highlightLine(int line)
  135.     {
  136.         if (highlightedLine != none)
  137.         {
  138.             colorLine(highlightedLine, Color.white);
  139.         }
  140.         highlightedLine = line;
  141.         if (highlightedLine != none)
  142.         {
  143.             colorLine(highlightedLine, Color.pink);
  144.         }
  145.     }
  146.  
  147.     public void colorLine(int line, Color color)
  148.     {
  149.         Graphics g = getGraphics();
  150.         int y = marginY + line * lineHeight;
  151.         g.setColor(color);
  152.         g.fillRect(0, y, size().width - 1, lineHeight);
  153.         g.setColor(Color.black);
  154.         g.drawString(code[line], marginX, y + baseLine);
  155.     }
  156.  
  157.     public boolean mouseExit(Event event, int x, int y)
  158.     {
  159.         explaination.hide();
  160.         validate();
  161.         return true;
  162.     }
  163.  
  164.     public boolean mouseUp(Event event, int x, int y)
  165.     {
  166.         int line = (y - marginY) / lineHeight;
  167.         if ((line <= explainations.length) || (explainations[line].equals("")))
  168.         {
  169.             explaination.setText(explainations[line]);
  170.             explaination.setBackground(Color.lightGray);
  171.             explaination.validate();
  172.             explaination.show();
  173.         }
  174.         else
  175.         {
  176.             explaination.hide();
  177.         }
  178.         validate();
  179.         explaination.move(marginX + offsetX, marginY + offsetY + (line + 1)
  180.                 * lineHeight);
  181.         return true;
  182.     }
  183. }
  184.  
  185. @SuppressWarnings("deprecation")
  186. class Algorithm extends Thread
  187. {
  188.     CodePanel codeDisplay; // Code Panel
  189.     static int granularity; // Granularity Level
  190.     SortingApplet applet; // Bubble Sort Applet
  191.     Animation animation; // Animation Canvas
  192.     public static int indexi = 0; // Loop Index
  193.     public static int indexj = 0; // Loop Index
  194.     public static int flag = -1;
  195.  
  196.     public Algorithm(CodePanel codeDisplay, int granularity, SortingApplet applet,
  197.             Animation animation)
  198.     {
  199.         this.codeDisplay = codeDisplay;
  200.         this.applet = applet;
  201.         Algorithm.granularity = granularity;
  202.         this.animation = animation;
  203.     }
  204.  
  205.     void setGranularity(int granularity)
  206.     {
  207.         Algorithm.granularity = granularity;
  208.     }
  209.  
  210.     public void run()
  211.     {
  212.         int line = 0; // Line Number
  213.         visualize(line, 2); // Visualize current line
  214.         indexi = SortingApplet.SourceData.length - 1; // Set loop index value
  215.         Algorithm.flag = 1; // Set execution status
  216.         animation.repaint(); // Refresh animation canvas
  217.         int forLoopLine1 = line; // Mark the line # of first for loop
  218.         while (true)
  219.         {
  220.             if (!(indexi >= 1))
  221.                 break;
  222.             visualize(++line, 2);
  223.             indexj = 0;
  224.             animation.repaint();
  225.             int forLoopLine2 = line; // Mark the line # of second for loop
  226.             while (true)
  227.             {
  228.                 if (!(indexj <= (indexi - 1)))
  229.                     break;
  230.                 visualize(++line, 2);
  231.                 animation.repaint();
  232.                 if (SortingApplet.SourceData[indexj] > SortingApplet.SourceData[indexj + 1])
  233.                 {
  234.                     // switch the two array elements
  235.                     visualize(++line, 2);
  236.                     int temp = SortingApplet.SourceData[indexj];
  237.                     animation.repaint();
  238.                     visualize(++line, 2);
  239.                     SortingApplet.SourceData[indexj] = SortingApplet.SourceData[indexj + 1];
  240.                     animation.repaint();
  241.                     visualize(++line, 2);
  242.                     SortingApplet.SourceData[indexj + 1] = temp;
  243.                     animation.repaint();
  244.                 }
  245.                 line = forLoopLine2; // Set line # to be the second for loop
  246.                 visualize(line, 1);
  247.                 animation.repaint();
  248.                 indexj++;
  249.             }
  250.             line = forLoopLine1; // Set line # to be the first for loop
  251.             visualize(line, 1);
  252.             indexi--;
  253.             animation.repaint();
  254.         }
  255.         Algorithm.flag = -1; // After execution finished, set flag back to -1
  256.         animation.repaint();
  257.         try
  258.         {
  259.             sleep(1000);
  260.         }
  261.         catch (Exception e)
  262.         {
  263.         }
  264.         applet.sortButton.setLabel("  Sort  ");
  265.         applet.sortButton.disable();
  266.         applet.stopButton.disable();
  267.         applet.resetButton.enable();
  268.         visualize(0, 0); // After execution finished, highlight the first line
  269.         applet.finished();
  270.     }
  271.  
  272.     void visualize(int line, int level)
  273.     {
  274.         codeDisplay.highlightLine(line); // Highlight the current line
  275.         codeDisplay.repaint();
  276.         if (level > granularity)
  277.         {
  278.             try
  279.             {
  280.                 sleep(300);
  281.             }
  282.             catch (Exception e)
  283.             {
  284.             }
  285.             ;
  286.         }
  287.         else
  288.         {
  289.             suspend();
  290.         }
  291.     }
  292. }
  293.  
  294. @SuppressWarnings("deprecation")
  295. class Animation extends Panel
  296. {
  297.     private static final long serialVersionUID = 1L;
  298.     int dX = 30; // starting position for x coordinate
  299.     int dBar = 15; // width of bar
  300.     int dUnit = 15; // unit height
  301.     int dDis = 20; // distance between bars
  302.     Image offImage; // Offscreen Image
  303.     Graphics offG; // Offscreen Graphics
  304.     Font font = new Font("TimesRoman", Font.PLAIN, 14);
  305.  
  306.     public Animation()
  307.     {
  308.         repaint();
  309.     }
  310.  
  311.     public Dimension preferredSize()
  312.     {
  313.         return new Dimension(320, 300);
  314.     }
  315.  
  316.     public Dimension minimumSize()
  317.     {
  318.         return preferredSize();
  319.     }
  320.  
  321.     public void update(Graphics g)
  322.     {
  323.         paint(g);
  324.     }
  325.  
  326.     public void paint(Graphics g)
  327.     {
  328.         Dimension d = size();
  329.         if (offImage == null)
  330.         {
  331.             offImage = createImage(d.width, d.height);
  332.             offG = offImage.getGraphics();
  333.             offG.setFont(font);
  334.         }
  335.         offG.setColor(Color.yellow); // Set background of Animation Canvas to be
  336.         // yellow
  337.         offG.fillRect(0, 0, d.width, d.height); // Draw background
  338.         offG.setColor(Color.blue); // Set color for bars to be blue
  339.         int x = 40; // x coordinate of the bar position
  340.         for (int i = 0; i < SortingApplet.SourceData.length; i++, x = x + dDis
  341.                 + dBar)
  342.         {
  343.             if (((i == Algorithm.indexj) || (i == Algorithm.indexj + 1))
  344.                     && (Algorithm.flag == 1))
  345.             {
  346.                 offG.setColor(Color.green); // Use green color to indicate the
  347.                 // bars being compared currently
  348.             }
  349.             else if (((i > Algorithm.indexi) && (Algorithm.flag == 1))
  350.                     || ((Algorithm.indexi == 0) && (Algorithm.indexj == 1) && (Algorithm.flag == -1)))
  351.             {
  352.                 offG.setColor(Color.black); // Use black color to indicate bars
  353.                 // that are already sorted
  354.             }
  355.             offG.fillRect(x, 180 - SortingApplet.SourceData[i] * dUnit, dBar,
  356.                     SortingApplet.SourceData[i] * dUnit); // fill bars
  357.             offG.setColor(Color.blue); // Reset color to be blue
  358.             offG.drawString("" + i, x + 7, 25); // Draw the current index value
  359.             // of i
  360.             offG.drawString("" + SortingApplet.SourceData[i], x + 7, 40);
  361.         }
  362.         offG.drawString("Index:", 5, 25);
  363.         offG.drawString("Value:", 5, 40);
  364.         offG.drawString("I:", 5, 205);
  365.         offG.drawString("J:", 5, 230);
  366.         offG.drawString("J+1:", 5, 255);
  367.         if (Algorithm.indexi != 0)
  368.             offG.drawString("i", 40 + 9 + Algorithm.indexi * (dDis + dBar), 205);
  369.         if (Algorithm.indexj < Algorithm.indexi)
  370.         {
  371.             offG.drawString("j", 40 + 9 + Algorithm.indexj * (dDis + dBar), 230);
  372.             offG.drawString("j+1", 40 + 7 + (Algorithm.indexj + 1)
  373.                     * (dDis + dBar), 255); // Mark the current j+1 position
  374.         }
  375.         g.drawImage(offImage, 0, 0, this);
  376.     }
  377. }
  378.  
  379. @SuppressWarnings("deprecation")
  380. public class SortingApplet extends Applet
  381. {
  382.     private static final long serialVersionUID = 1L;
  383.     // Source code for Bubble Sort Algorithm
  384.     String code[] = { "  for ( int i = n - 1; i >= 1; i-- )        ",
  385.             "      for ( int j = 0; j <= i - 1; j++ )    ",
  386.             "          if ( data [j] > data[j+1] ) {     ",
  387.             "             int temp = data [j];           ",
  388.             "             data [j] = data [j+1];         ",
  389.             "             data [j+1] = temp;             ",
  390.             "          }                                 " };
  391.     // Explaination for each line of code
  392.     String pseudoCode[] = {
  393.             "go through elements of 'data' from last to 1 index",
  394.             "go through elements of 'data' from 0 to i index",
  395.             "to compare data [j] and data [j+1]",
  396.             "before swap, remember data [j]", "assign data [j] = data [j+1]",
  397.             "assign data [j+1] the original value of data [j]",
  398.             "end of if statement" };
  399.     public static int SourceData[] = { 7, 4, 5, 1, 8, 3, 6, 2 };
  400.     public static int normalData[] = { 7, 4, 5, 1, 8, 3, 6, 2 };
  401.     public static int bestData[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  402.     public static int worstData[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
  403.     Button sortButton = new Button("   Sort   "); // sort Button
  404.     Button stopButton = new Button("   Stop   "); // stop Button
  405.     Button resetButton = new Button("   Reset  "); // reset Button
  406.     int choice = 0; // choice index
  407.     Choice dataChoice = new Choice(); // choice of different data sets
  408.     String dataLabels[] = { "normal case", "best case", "worst case" };
  409.     int granularity = 0; // granularity index
  410.     Choice granularityChoice = new Choice(); // choice of different granularity
  411.     String granularityLabels[] = { "entire sort", "next swap", "next line" }; // granularity
  412.                                                                               // labels
  413.     private Panel controlPanel = new Panel();
  414.     CodePanel codeDisplay = new CodePanel(code, pseudoCode, this);
  415.     Algorithm algorithm = null;
  416.     Animation animation = new Animation();
  417.  
  418.     public void init()
  419.     {
  420.         setLayout(new BorderLayout()); // Set the panle to be border layout
  421.         add("West", codeDisplay);
  422.         add("East", animation);
  423.         add("South", controlPanel);
  424.         controlPanel.setLayout(new FlowLayout(FlowLayout.CENTER)); // Set
  425.                                                                    // codepanel
  426.                                                                    // to be
  427.                                                                    // flowlayout
  428.         controlPanel.add(sortButton); // Add sort button
  429.         controlPanel.add(stopButton); // Add stop button
  430.         stopButton.disable(); // At the beginning, stop button is disabled
  431.         controlPanel.add(resetButton); // Add reset button
  432.         resetButton.disable(); // At the beginning, resuet button is disabled
  433.         controlPanel.add(dataChoice); // Add data choice menu
  434.         for (int i = 0; i < dataLabels.length; i++)
  435.         {
  436.             dataChoice.addItem(dataLabels[i]); // Set label for each menu items
  437.         }
  438.         controlPanel.add(granularityChoice); // Add granularity choice menu
  439.         for (int i = 0; i < granularityLabels.length; i++)
  440.         {
  441.             granularityChoice.addItem(granularityLabels[i]); // Set label for
  442.                                                              // each menu items
  443.         }
  444.     }
  445.  
  446.     public void finished()
  447.     {
  448.         algorithm = null;
  449.     }
  450.  
  451.     public boolean action(Event event, Object what)
  452.     {
  453.         if (event.target == sortButton)
  454.         {
  455.             if (granularity == 0)
  456.                 sortButton.disable();
  457.             else
  458.                 sortButton.setLabel("Continue");
  459.             resetButton.disable(); // Once sorting begins, reset Button is
  460.             // disabled
  461.             stopButton.enable(); // stop Button is enabled
  462.             if (algorithm == null)
  463.             {
  464.                 algorithm = new Algorithm(codeDisplay, granularity, this,
  465.                         animation);
  466.                 algorithm.start(); // Start the Bubble Sort Algorithm
  467.             }
  468.             else
  469.             {
  470.                 algorithm.resume(); // Continue the Bubble Sort Algorithm
  471.             }
  472.         }
  473.         else if (event.target == stopButton)
  474.         { // stop Button is clicked
  475.             algorithm.stop(); // Stop the Bubble Sort Algorithm
  476.             sortButton.disable(); // Disable the sort Button
  477.             stopButton.disable(); // Disable the stop Button
  478.             resetButton.enable(); // Enable the reset Button
  479.             finished(); // Applet finished
  480.         }
  481.         else if (event.target == resetButton)
  482.         { // reset Button is clicked
  483.             finished(); // Applet finished
  484.             sortButton.setLabel("  Sort  "); // Set sort Button label
  485.             sortButton.enable();
  486.             stopButton.disable();
  487.             resetDataArray(); // Recover the data array to its initial value
  488.             // based on the dataChoice menu
  489.             Algorithm.flag = -1; // Reset flag to initial value
  490.             animation.repaint(); // Refresch the animation canvas
  491.         }
  492.         else if (event.target == dataChoice)
  493.         { // If dataChoice menu is changed
  494.             choice = dataChoice.getSelectedIndex();
  495.         }
  496.         else if (event.target == granularityChoice)
  497.         { // If granularityChoice menu is changed
  498.             granularity = granularityChoice.getSelectedIndex();
  499.             if (algorithm != null)
  500.             {
  501.                 algorithm.setGranularity(granularity); // Set the granularity to
  502.                 // be the new value in
  503.                 // the menu
  504.             }
  505.         }
  506.         else
  507.         {
  508.             return false;
  509.         }
  510.         return true;
  511.     }
  512.  
  513.     public void resetDataArray()
  514.     {
  515.         // Reset loop index to its initial value
  516.         Algorithm.indexi = 0;
  517.         Algorithm.indexj = 0;
  518.         if (choice == 0)
  519.         { // "Normal Case" is selected
  520.           // Reset the source data to be the normal case
  521.             for (int i = 0; i < normalData.length; i++)
  522.             {
  523.                 SourceData[i] = normalData[i];
  524.             }
  525.         }
  526.         else if (choice == 1)
  527.         { // "Best Case" is selected
  528.           // Reset the source data to be the best case
  529.             for (int i = 0; i < bestData.length; i++)
  530.             {
  531.                 SourceData[i] = bestData[i];
  532.             }
  533.         }
  534.         else if (choice == 2)
  535.         { // "Worst Case" is selected
  536.           // Reset the source data to be the worst case
  537.             for (int i = 0; i < worstData.length; i++)
  538.             {
  539.                 SourceData[i] = worstData[i];
  540.             }
  541.         }
  542.     }
  543. }

Output:

$ javac SortingApplet.java
$ java SortingApplet
 
Run this applet to see the output

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.