├── assets
└── mvp1.gif
├── AlgorithmVisualizer.java
├── README.md
├── examples
├── ExampleMenu1.java
├── Algorithm.java
└── InsertionSort.txt
├── Main.java
├── Sorting.java
└── SortingAlgorithm.java
/assets/mvp1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/algorithm-visualizer-java/HEAD/assets/mvp1.gif
--------------------------------------------------------------------------------
/AlgorithmVisualizer.java:
--------------------------------------------------------------------------------
1 | /** AlgorithmVisualizer.java is responsibe for running the project */
2 | public class AlgorithmVisualizer {
3 | public static void main(String[] args){
4 | new Main(); // referencing to the Main Class
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Algorithm Visualizer in Java
2 |
3 | Developed by [@Rustam-Z](https://github.com/Rustam-Z) and [@Alimov-8](https://github.com/Alimov-8)
4 |
5 | Demo video: https://youtu.be/huR1NSwUnAY
6 |
7 | Finish date: December 13, 2020
8 |
9 | ## Project Features
10 | - Sorting Algorithms Visualizer `DONE`
11 | - [Picture Puzzle Sorter](https://www.youtube.com/watch?v=Bc0sVtB_-ak) `TODO`
12 | - [Pathfinding algorithm](https://clementmihailescu.github.io/Pathfinding-Visualizer/) `TODO`
13 |
14 | ## First Prototype
15 |
16 |
17 | ## How to run?
18 | ```
19 | javac AlgorithmVisualizer.java
20 | java AlgorithmVisualizer
21 | ```
22 |
23 | ## Skills Gained
24 | - Multi-Threading using Swing Worker
25 | - Customizing Swing Components
26 | - Working with Graphics 2D
27 | - Different sorting algorithms
28 |
29 | ## References:
30 | - https://clementmihailescu.github.io/Sorting-Visualizer/
31 | - https://www.geeksforgeeks.org/java-swing-jmenubar/
32 | - https://stackoverflow.com/questions/31094904/jmenu-not-appearing-until-window-is-resized
33 | - https://stackoverflow.com/questions/4716372/java-how-do-i-close-a-jframe-while-opening-another-one
34 | - First prototype video: https://www.youtube.com/watch?v=RxjXC1SM1A4
35 | - https://stackoverflow.com/questions/4246351/creating-random-colour-in-java
36 | - https://stackoverflow.com/questions/782265/how-do-i-use-swingworker-in-java
37 | - https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
38 | - https://stackoverflow.com/questions/1097366/java-swing-revalidate-vs-repaint
39 | - Merge sort: https://www.baeldung.com/java-merge-sort
40 | - http://www.java2s.com/Tutorials/Java/Swing/JSlider/Add_change_event_listener_to_a_JSlider_in_Java.htm
41 |
--------------------------------------------------------------------------------
/examples/ExampleMenu1.java:
--------------------------------------------------------------------------------
1 | // Java program Program to add a menubar
2 | // and add menuitems, submenu items and also add
3 | // ActionListener to menu items
4 | import java.awt.*;
5 | import javax.swing.*;
6 | import java.awt.event.*;
7 |
8 | public class ExampleMenu1 extends JFrame implements ActionListener {
9 | // menubar
10 | static JMenuBar mb;
11 |
12 | // JMenu
13 | static JMenu x, x1;
14 |
15 | // Menu items
16 | static JMenuItem m1, m2, m3, s1, s2;
17 |
18 | // create a frame
19 | static JFrame f;
20 |
21 | // a label
22 | static JLabel l;
23 |
24 | // main class
25 | public static void main(String[] args) {
26 |
27 | // create an object of the class
28 | ExampleMenu1 m = new ExampleMenu1();
29 |
30 | // create a frame
31 | f = new JFrame("Menu demo");
32 |
33 | // create a label
34 | l = new JLabel("no task ");
35 |
36 | // create a menubar
37 | mb = new JMenuBar();
38 |
39 | // create a menu
40 | x = new JMenu("Menu");
41 | x1 = new JMenu("submenu");
42 |
43 | // create menuitems
44 | m1 = new JMenuItem("MenuItem1");
45 | m2 = new JMenuItem("MenuItem2");
46 | m3 = new JMenuItem("MenuItem3");
47 | s1 = new JMenuItem("SubMenuItem1");
48 | s2 = new JMenuItem("SubMenuItem2");
49 |
50 | // add ActionListener to menuItems
51 | m1.addActionListener(m);
52 | m2.addActionListener(m);
53 | m3.addActionListener(m);
54 | s1.addActionListener(m);
55 | s2.addActionListener(m);
56 |
57 | // add menu items to menu
58 | x.add(m1);
59 | x.add(m2);
60 | x.add(m3);
61 | x1.add(s1);
62 | x1.add(s2);
63 |
64 | // add submenu
65 | x.add(x1);
66 |
67 | // add menu to menu bar
68 | mb.add(x);
69 |
70 | // add menubar to frame
71 | f.setJMenuBar(mb);
72 |
73 | // add label
74 | f.add(l);
75 |
76 | // set the size of the frame
77 | f.setSize(500, 500);
78 | f.setVisible(true);
79 | }
80 | public void actionPerformed(ActionEvent e)
81 | {
82 | String s = e.getActionCommand();
83 |
84 | // set the label to the menuItem that is selected
85 | l.setText(s + " selected");
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/Main.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Main.java includes:
3 | * - Menus and menu items
4 | * - Main frame
5 | */
6 |
7 | import java.awt.event.*;
8 | import javax.swing.*;
9 |
10 | public class Main extends JFrame {
11 | // Menubar
12 | static JMenuBar menuBar;
13 |
14 | // JMenu
15 | static JMenu mainMenu, helpDesk;
16 |
17 | // Menu items
18 | static JMenuItem menuItem1, menuItem2, menuItem3, menuItem4;
19 |
20 | Main() {
21 | // Create a menubar
22 | menuBar = new JMenuBar();
23 |
24 | // Create a menu
25 | mainMenu = new JMenu("Menu");
26 | helpDesk = new JMenu("Help");
27 |
28 | // Create a menu items
29 | menuItem1 = new JMenuItem("Path Finding"); // Its for future vision
30 | menuItem2 = new JMenuItem("Sorting Techniques"); // Done
31 | menuItem3 = new JMenuItem("Puzzle Sorting"); // Its for future vision
32 | menuItem4 = new JMenuItem("How it Works"); // About
33 |
34 | ListenerClass listener = new ListenerClass();
35 |
36 | // Register listeners
37 | menuItem1.addActionListener(listener);
38 | menuItem2.addActionListener(listener);
39 | menuItem3.addActionListener(listener);
40 |
41 | // Add menu items to menu
42 | mainMenu.add(menuItem1);
43 | mainMenu.add(menuItem2);
44 | mainMenu.add(menuItem3);
45 | helpDesk.add(menuItem4);
46 |
47 | // Add menu to menu bar
48 | menuBar.add(mainMenu);
49 | menuBar.add(helpDesk);
50 |
51 | // Add menubar to frame
52 | setJMenuBar(menuBar);
53 |
54 | setTitle("Eightsoft");
55 | setSize(800, 800);
56 | setLocation(300, 5);
57 | setVisible(true);
58 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
59 | }
60 |
61 | class ListenerClass implements ActionListener {
62 | String value;
63 |
64 | // Project Main Logic (Moving Panels)
65 | public void actionPerformed(ActionEvent e) {
66 | if (e.getSource() == menuItem1) {
67 | System.out.println(" Path Finding Algorith (We will add it in future for portfolio)");
68 | }
69 | else if (e.getSource() == menuItem2) {
70 | // Creating Object
71 | new Sorting();
72 | System.out.println("Menu Item 2 choosed");
73 | }
74 | else if (e.getSource() == menuItem2) {
75 | System.out.println(" Picture pazzling algorith (We will add it in future for portfolio)");
76 | }
77 | setVisible(false); // will close the previous window
78 | }
79 | }
80 |
81 | } // Menu
82 |
--------------------------------------------------------------------------------
/examples/Algorithm.java:
--------------------------------------------------------------------------------
1 | import javax.swing.*;
2 | import java.awt.*;
3 | import java.awt.event.*;
4 | import java.util.*;
5 |
6 |
7 | public class Algorithm extends JFrame{
8 | // Menu Bar
9 | JMenuBar menuBar =new JMenuBar();
10 | JMenu mainMenu = new JMenu("Menu");
11 | JMenu helpDesk = new JMenu("Help");
12 | JMenuItem menu1 = new JMenuItem("Path Finding");
13 | JMenuItem menu2 = new JMenuItem("Sorting Techniques");
14 | JMenuItem menu3 = new JMenuItem("Pic Puzzle Sorting");
15 | JMenuItem menu4 = new JMenuItem("How it Works");
16 |
17 | Algorithm(){
18 | // Adding MenuBar to the frame
19 | mainMenu.add(menu1); mainMenu.add(menu2); mainMenu.add(menu3); helpDesk.add(menu4);
20 | menuBar.add(mainMenu); menuBar.add(helpDesk);
21 | setJMenuBar(menuBar);
22 |
23 | // Register listeners
24 | ListenerClass listener = new ListenerClass();
25 | menu1.addActionListener(listener);
26 | menu2.addActionListener(listener);
27 | menu3.addActionListener(listener);
28 | }
29 |
30 | public static void main(String[] args){
31 | JFrame frame = new Algorithm();
32 | frame.setTitle("Project 2020 by EightSoft Academy");
33 | frame.setSize(700,500);
34 | frame.setLocation(200, 100);
35 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
36 | frame.setVisible(true);
37 | }
38 |
39 | class ListenerClass implements ActionListener {
40 | String value;
41 |
42 | // Project Main Logic (Moving Panels)
43 | public void actionPerformed(ActionEvent e) {
44 | if (e.getSource() == menu1) {
45 | Sorting sort = new Sorting();
46 | }
47 | }
48 | }
49 |
50 | }
51 |
52 |
53 | class Sorting {
54 | JFrame frameSorting = new JFrame("Sorting");
55 | // Values
56 | ArrayList list=new ArrayList();//Creating arraylist
57 |
58 | // Sorting Buttons
59 | JButton jbtRandomize, jbtReset, jbtBubble, jbtInsertion, jbtSelection, jbtStart; // Sorting Buttons
60 | JPanel p1Sorting, p2Sorting;
61 | Random rand = new Random();
62 |
63 | Sorting(){
64 | // Buttons for sorting
65 | jbtRandomize = new JButton("Randomize");//create button
66 | jbtReset = new JButton("Reset");//create button
67 | jbtBubble = new JButton("Bubble sort");//create button
68 | jbtInsertion = new JButton("Insertion sort");//create button
69 | jbtSelection = new JButton("Selection sort");//create button
70 | jbtStart = new JButton("Start");//create button
71 |
72 | // Panel for buttons
73 | p1Sorting = new JPanel();
74 | p1Sorting.setLayout(new GridLayout(7,1));
75 |
76 | // Adding Buttons to the panel
77 | p1Sorting.add(jbtRandomize); p1Sorting.add(jbtReset); p1Sorting.add(jbtSelection);
78 | p1Sorting.add(jbtBubble); p1Sorting.add(jbtInsertion); p1Sorting.add(jbtStart);
79 |
80 | // Adding frame
81 | frameSorting.add(p1Sorting, BorderLayout.WEST);
82 | frameSorting.setTitle("Sorting");
83 | frameSorting.setSize(700,500);
84 | frameSorting.setLocation(200, 100);
85 | frameSorting.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
86 | frameSorting.setVisible(true);
87 | }
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/examples/InsertionSort.txt:
--------------------------------------------------------------------------------
1 | package examples;
2 |
3 | // Insertion sort visualizer
4 |
5 | import java.awt.Color;
6 | import java.awt.Dimension;
7 | import java.awt.Graphics;
8 | import java.awt.Graphics2D;
9 | import java.awt.geom.Rectangle2D;
10 | import java.util.Random;
11 |
12 | import javax.swing.JFrame;
13 | import javax.swing.JPanel;
14 | import javax.swing.SwingUtilities;
15 | import javax.swing.SwingWorker;
16 |
17 | public class InsertionSort extends JPanel {
18 | private final int WIDTH = 800, HEIGHT = WIDTH * 9 /16;
19 | private final int SIZE = 200; // the number if sorting elements
20 | private final float BAR_WIDTH = (float)WIDTH / SIZE; // bar width
21 | private float[] bar_height = new float[SIZE]; // height of bars
22 | private SwingWorker shuffler, sorter;
23 | private int current_index, traversing_index;
24 |
25 | InsertionSort() {
26 | setBackground(Color.BLACK);
27 | setPreferredSize(new Dimension(WIDTH, HEIGHT));
28 | initBarHeight(); // initialize the height of each bar
29 | initSorter();
30 | initShuffler();
31 | }
32 |
33 | @Override
34 | public void paintComponent(Graphics g) {
35 | super.paintComponent(g);
36 |
37 | Graphics2D g2d = (Graphics2D)g;
38 | g2d.setColor(Color.CYAN);
39 | Rectangle2D.Float bar;
40 | for(int i = 0; i < SIZE; i++ ) {
41 | bar = new Rectangle2D.Float(i * BAR_WIDTH, 0, BAR_WIDTH, bar_height[i]);
42 | g2d.fill(bar); // g2d.draw(bar);
43 | }
44 |
45 | g2d.setColor(Color.RED);
46 | bar = new Rectangle2D.Float(current_index * BAR_WIDTH, 0, BAR_WIDTH, bar_height[current_index]);
47 | g2d.fill(bar);
48 |
49 | g2d.setColor(Color.GREEN);
50 | bar = new Rectangle2D.Float(traversing_index * BAR_WIDTH, 0, BAR_WIDTH, bar_height[traversing_index]);
51 | g2d.fill(bar);
52 | }
53 |
54 | public void initBarHeight() {
55 | float interval = (float)HEIGHT / SIZE;
56 | for(int i = 0; i < SIZE; i++) {
57 | bar_height[i] = i * interval;
58 | }
59 | }
60 |
61 | public void initSorter() {
62 | sorter = new SwingWorker<>() {
63 | @Override
64 | public Void doInBackground() throws InterruptedException {
65 | for(current_index = 1; current_index < SIZE; current_index++) {
66 | traversing_index = current_index;
67 | while(traversing_index > 0 && bar_height[traversing_index] < bar_height[traversing_index - 1]) {
68 | swap(traversing_index, traversing_index - 1);
69 | traversing_index--;
70 |
71 | Thread.sleep(1);
72 | repaint();
73 | }
74 | }
75 | current_index = 0;
76 | traversing_index = 0;
77 |
78 | return null;
79 | }
80 | };
81 | }
82 |
83 | public void initShuffler() {
84 | shuffler = new SwingWorker<>() {
85 | @Override
86 | public Void doInBackground() throws InterruptedException {
87 | int middle = SIZE / 2;
88 | for (int i = 0, j = middle; i < middle; i++, j++) {
89 | int randow_index = new Random().nextInt(SIZE);
90 | swap(i, randow_index);
91 |
92 | randow_index = new Random().nextInt(SIZE);
93 | swap(j, randow_index);
94 |
95 | Thread.sleep(10);
96 | repaint();
97 | }
98 | return null;
99 | }
100 |
101 | @Override
102 | public void done() {
103 | super.done();
104 | sorter.execute();
105 | }
106 | };
107 | shuffler.execute();
108 | }
109 |
110 | public void swap(int indexA, int indexB) {
111 | float temp = bar_height[indexA];
112 | bar_height[indexA] = bar_height[indexB];
113 | bar_height[indexB] = temp;
114 | }
115 |
116 | public static void main(String args[]) {
117 | SwingUtilities.invokeLater(() -> {
118 | JFrame frame = new JFrame("Insertion Sort");
119 | //frame.setResizable(false);
120 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
121 | frame.setContentPane(new InsertionSort());
122 | frame.validate();
123 | frame.pack();
124 | frame.setLocationRelativeTo(null);
125 | frame.setVisible(true);
126 | });
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/Sorting.java:
--------------------------------------------------------------------------------
1 | // Main GUI part of Sorting.
2 |
3 | import javax.swing.*;
4 | import java.awt.*;
5 | import java.awt.event.*;
6 |
7 | import javax.swing.event.ChangeEvent;
8 | import javax.swing.event.ChangeListener;
9 |
10 | public class Sorting extends Main {
11 | // Object of the SortingAlgorithm, which includes the sorting algorithms
12 | SortingAlgorithm sortAlgo = new SortingAlgorithm();
13 |
14 | // Panels: pPanel1 - option bar, pPanel2 - visualization bar
15 | JPanel pPanel1, pPanel2;
16 |
17 | // Option buttons for choosing sorting techniques, speed, and size of array
18 | // Will be added to pPanel1
19 | JButton jbtRandomize, jbtMerge, jbtBubble, jbtInsertion, jbtSelection, jbtStart;
20 |
21 | // Progress Bar
22 | JProgressBar jb1;
23 |
24 | JSlider slider = new JSlider(0, 100, 2);
25 |
26 | public Sorting(){
27 | // Panel for options (bubble sort, insertion sort...)
28 | pPanel1 = new JPanel();
29 | pPanel1.setLayout(new GridLayout(1, 7));
30 | pPanel1.setBackground(Color.CYAN);
31 |
32 | // Panel for visualization part
33 | pPanel2 = new JPanel();
34 | pPanel2.setLayout(new BorderLayout());
35 |
36 | // Buttons
37 | jbtRandomize = new JButton("Randomize");
38 | jbtMerge = new JButton("Merge Sort");
39 | jbtBubble = new JButton("Bubble Sort");
40 | jbtInsertion = new JButton("Insertion Sort");
41 | jbtSelection = new JButton("Selection Sort");
42 | jbtStart = new JButton("Start");
43 | jbtStart.setBackground(Color.GRAY);
44 |
45 | // Slider
46 | // slider.setPreferredSize(new Dimension(150, 30));
47 | // slider.setMajorTickSpacing(50);
48 | // slider.setPaintTicks(false);
49 |
50 | // Adding elements to pPanel1
51 | pPanel1.add(jbtRandomize);
52 | pPanel1.add(jbtMerge); pPanel1.add(jbtSelection); pPanel1.add(jbtBubble); pPanel1.add(jbtInsertion);
53 | // pPanel1.add(jbtStart);
54 | pPanel1.add(slider, BorderLayout.WEST);
55 |
56 | // Adding elements to pPanel2
57 | pPanel2.add(sortAlgo, BorderLayout.CENTER);
58 |
59 | // Register listener, event handling
60 | ListenerClass listener = new ListenerClass();
61 | jbtRandomize.addActionListener(listener);
62 | jbtMerge.addActionListener(listener);
63 | jbtBubble.addActionListener(listener);
64 | jbtInsertion.addActionListener(listener);
65 | jbtSelection.addActionListener(listener);
66 | jbtStart.addActionListener(listener);
67 |
68 | // Add Panels to the Main JFrame
69 | add(pPanel1, BorderLayout.NORTH);
70 | add(pPanel2, BorderLayout.CENTER);
71 |
72 | // Slider settings
73 | slider.addChangeListener(new ChangeListener() {
74 | @Override
75 | public void stateChanged(ChangeEvent event) {
76 | int value = slider.getValue();
77 | sortAlgo.setSIZE(value);
78 | // Graphics g = new Graphics();
79 | // sortAlgo.initBarHeight();
80 | sortAlgo.BAR_WIDTH = (float)800 / sortAlgo.getSIZE(); // bar width
81 | sortAlgo.repaint();
82 | System.out.println(value);
83 |
84 | }
85 | });
86 | }
87 |
88 | class ListenerClass implements ActionListener {
89 | // Handles the Button operations
90 |
91 | public void actionPerformed(ActionEvent e) {
92 |
93 | if (e.getSource() == jbtRandomize) {
94 | sortAlgo.initShuffler();
95 | }
96 | else if (e.getSource() == jbtMerge) {
97 | sortAlgo.mergeSort(); // Merge sort algorithm
98 | sortAlgo.initShuffler(); // shuffling
99 | }
100 | else if (e.getSource() == jbtBubble) {
101 | sortAlgo.bubbleSort(); // Bubble sort algorithm
102 | sortAlgo.initShuffler(); // shuffling
103 | }
104 | else if (e.getSource() == jbtInsertion) {
105 | sortAlgo.insertionSort(); // Insertion algorithm
106 | sortAlgo.initShuffler(); // shuffling
107 | }
108 | else if (e.getSource() == jbtSelection) {
109 | sortAlgo.selectionSort(); // Insertion algorithm
110 | sortAlgo.initShuffler(); // shuffling
111 | }
112 | else if (e.getSource() == jbtStart) {
113 | System.out.println("jbtStart button clicked");
114 | }
115 | }
116 | } // ListenerClass
117 |
118 | } // Sorting
119 |
--------------------------------------------------------------------------------
/SortingAlgorithm.java:
--------------------------------------------------------------------------------
1 | // Implementation of Sorting algorithms
2 |
3 | import java.awt.Color;
4 | import java.awt.Dimension;
5 | import java.awt.Graphics;
6 | import java.awt.Graphics2D;
7 | import java.awt.geom.Rectangle2D;
8 | import java.util.Random;
9 |
10 | import javax.swing.JPanel;
11 | import javax.swing.SwingWorker;
12 |
13 | public class SortingAlgorithm extends JPanel {
14 | private final int WIDTH = 800, HEIGHT = WIDTH * 9 / 16;
15 | public int SIZE = 100; // the number if sorting elements
16 | public float BAR_WIDTH = (float)WIDTH / SIZE; // bar width
17 | private float[] bar_height = new float[SIZE]; // height of bars
18 | private SwingWorker shuffler, sorter;
19 | private int current_index, traversing_index; // needed for following colloring the items
20 |
21 | SortingAlgorithm() {
22 | setBackground(Color.BLACK);
23 | setPreferredSize(new Dimension(WIDTH, HEIGHT));
24 | initBarHeight(); // initialize the height of each bar
25 | // initShuffler(); // shuffle each bar
26 | }
27 |
28 | // setter for SIZE
29 | public void setSIZE(int SIZE) {
30 | this.SIZE = SIZE;
31 | }
32 |
33 | // getter for SIZE
34 | int getSIZE() {
35 | return SIZE;
36 | }
37 |
38 | // repaint() will automaticly call this function
39 | // needed for coloring
40 | @Override
41 | public void paintComponent(Graphics g) {
42 | super.paintComponent(g);
43 |
44 | // Create randomizer
45 | Random random = new Random();
46 |
47 | // Drawing the rectangles
48 | Graphics2D g2d = (Graphics2D)g;
49 | g2d.setColor(Color.CYAN);
50 | Rectangle2D.Float bar;
51 |
52 | for(int i = 0; i < getSIZE(); i++ ) {
53 | // random colors
54 | // final float hue = random.nextFloat();
55 | // final float saturation = 0.9f; //1.0 for brilliant, 0.0 for dull
56 | // final float luminance = 1.0f; //1.0 for brighter, 0.0 for black
57 |
58 | // g2d.setColor(Color.getHSBColor(hue, saturation, luminance));
59 | bar = new Rectangle2D.Float(i * BAR_WIDTH, 0, BAR_WIDTH-1, bar_height[i]);
60 | g2d.fill(bar); // g2d.draw(bar);
61 | }
62 |
63 | // Color setter for the current object
64 | g2d.setColor(Color.RED);
65 | bar = new Rectangle2D.Float(current_index * BAR_WIDTH, 0, BAR_WIDTH, bar_height[current_index]);
66 | g2d.fill(bar);
67 |
68 | // Color setter for the traversing object
69 | g2d.setColor(Color.YELLOW);
70 | bar = new Rectangle2D.Float(traversing_index * BAR_WIDTH, 0, BAR_WIDTH, bar_height[traversing_index]);
71 | g2d.fill(bar);
72 | }
73 |
74 | public void insertionSort() {
75 | /*Insertion sort algorithm*/
76 | // Multithreading used for hadling the sorting
77 | sorter = new SwingWorker<>() {
78 | @Override
79 | public Void doInBackground() throws InterruptedException { // function for calling multithreading
80 | // Insertion sort algorithm starts
81 | for(current_index = 1; current_index < getSIZE(); current_index++) {
82 | traversing_index = current_index;
83 | while(traversing_index > 0 && bar_height[traversing_index] < bar_height[traversing_index - 1]) {
84 | swap(traversing_index, traversing_index - 1);
85 | traversing_index--;
86 |
87 | Thread.sleep(10); // controls the speed
88 | repaint(); // we need it because we ofter replace the contents of a JPanel
89 | }
90 | }
91 | current_index = 0;
92 | traversing_index = 0;
93 |
94 | return null;
95 | }
96 | };
97 | }
98 |
99 | public void bubbleSort() {
100 | /*Bubble sorting algorithm*/
101 | sorter = new SwingWorker<>() {
102 | @Override
103 | public Void doInBackground() throws InterruptedException {
104 | for(current_index = 0; current_index < getSIZE(); current_index++) {
105 | for(traversing_index = 1; traversing_index < (getSIZE() - current_index); traversing_index++) {
106 | if(bar_height[traversing_index - 1] > bar_height[traversing_index]) {
107 | swap(traversing_index, traversing_index - 1);
108 | traversing_index--; // just for annimation
109 |
110 | Thread.sleep(10); // controls the speed
111 | repaint(); // we need it because we ofter replace the contents of a JPanel
112 | }
113 | }
114 | }
115 | current_index = 0;
116 | traversing_index = 0;
117 |
118 | return null;
119 | }
120 | };
121 | }
122 |
123 | public void mergeSort() {
124 | /*Merge sorting algorithm*/
125 | // Change code from bubbleSort to mergeSort
126 | // TODO
127 |
128 | sorter = new SwingWorker<>() {
129 | @Override
130 | public Void doInBackground() throws InterruptedException {
131 | for(current_index = 0; current_index < getSIZE(); current_index++) {
132 | for(traversing_index = 1; traversing_index < (getSIZE() - current_index); traversing_index++) {
133 | if(bar_height[traversing_index - 1] > bar_height[traversing_index]) {
134 | swap(traversing_index, traversing_index - 1);
135 | traversing_index--; // just for annimation
136 |
137 | Thread.sleep(10); // controls the speed
138 | repaint(); // we need it because we ofter replace the contents of a JPanel
139 | }
140 | }
141 | }
142 | current_index = 0;
143 | traversing_index = 0;
144 |
145 | return null;
146 | }
147 | };
148 | }
149 |
150 |
151 | public void selectionSort() {
152 | /*Merge sorting algorithm*/
153 | // Change code from bubbleSort to mergeSort
154 | // TODO
155 |
156 | sorter = new SwingWorker<>() {
157 | @Override
158 | public Void doInBackground() throws InterruptedException {
159 | for(current_index = 0; current_index < getSIZE() - 1; current_index++) {
160 | int min_index = current_index;
161 | for(int traversing_index = current_index + 1; traversing_index < getSIZE(); traversing_index++) {
162 | if (bar_height[traversing_index] < bar_height[min_index]) {
163 | min_index = traversing_index;
164 | }
165 | }
166 | swap(current_index, min_index);
167 | Thread.sleep(10); // controls the speed
168 | repaint(); // we need it because we ofter replace the contents of a JPanel
169 | }
170 |
171 | current_index = 0;
172 | traversing_index = 0;
173 |
174 | return null;
175 | }
176 | };
177 | }
178 |
179 | public void initShuffler() {
180 | /*Shuffles each bar*/
181 | shuffler = new SwingWorker<>() {
182 | @Override
183 | public Void doInBackground() throws InterruptedException {
184 | int middle = getSIZE() / 2;
185 | for (int i = 0, j = middle; i < middle; i++, j++) {
186 | int randow_index = new Random().nextInt(getSIZE());
187 | swap(i, randow_index);
188 |
189 | randow_index = new Random().nextInt(getSIZE());
190 | swap(j, randow_index);
191 |
192 | Thread.sleep(10); // controls the speed
193 | repaint(); // we need it because we ofter replace the contents of a JPanel
194 | }
195 | return null;
196 | }
197 | // after finishing the process
198 | @Override
199 | public void done() {
200 | super.done();
201 | sorter.execute();
202 | }
203 | };
204 | shuffler.execute();
205 | }
206 |
207 | public void initBarHeight() {
208 | /*Initialize the height of each bar*/
209 | float interval = (float)HEIGHT / getSIZE();
210 | for(int i = 0; i < getSIZE(); i++) {
211 | bar_height[i] = i * interval;
212 | }
213 | }
214 |
215 | public void swap(int indexA, int indexB) {
216 | /*Swaps the elements*/
217 | float temp = bar_height[indexA];
218 | bar_height[indexA] = bar_height[indexB];
219 | bar_height[indexB] = temp;
220 | }
221 | }
--------------------------------------------------------------------------------