@@ -16,23 +16,27 @@ public class SortingAlgorithm extends JPanel {
1616 public float BAR_WIDTH = (float )WIDTH / SIZE ; // bar width
1717 private float [] bar_height = new float [SIZE ]; // height of bars
1818 private SwingWorker <Void , Void > shuffler , sorter ;
19- private int current_index , traversing_index ;
19+ private int current_index , traversing_index ;// needed for following colloring the items
2020
2121 SortingAlgorithm () {
2222 setBackground (Color .BLACK );
2323 setPreferredSize (new Dimension (WIDTH , HEIGHT ));
2424 initBarHeight (); // initialize the height of each bar
2525 // initShuffler(); // shuffle each bar
2626 }
27- 27+ 28+ // setter for SIZE
2829 public void setSIZE (int SIZE ) {
2930 this .SIZE = SIZE ;
3031 }
3132
33+ // getter for SIZE
3234 int getSIZE () {
3335 return SIZE ;
3436 }
3537
38+ // repaint() will automaticly call this function
39+ // needed for coloring
3640 @ Override
3741 public void paintComponent (Graphics g ) {
3842 super .paintComponent (g );
@@ -46,6 +50,7 @@ public void paintComponent(Graphics g) {
4650 Rectangle2D .Float bar ;
4751
4852 for (int i = 0 ; i < getSIZE (); i ++ ) {
53+ // random colors
4954 // final float hue = random.nextFloat();
5055 // final float saturation = 0.9f; //1.0 for brilliant, 0.0 for dull
5156 // final float luminance = 1.0f; //1.0 for brighter, 0.0 for black
@@ -68,17 +73,19 @@ public void paintComponent(Graphics g) {
6873
6974 public void insertionSort () {
7075 /*Insertion sort algorithm*/
76+ // Multithreading used for hadling the sorting
7177 sorter = new SwingWorker <>() {
7278 @ Override
73- public Void doInBackground () throws InterruptedException {
79+ public Void doInBackground () throws InterruptedException { // function for calling multithreading
80+ // Insertion sort algorithm starts
7481 for (current_index = 1 ; current_index < getSIZE (); current_index ++) {
7582 traversing_index = current_index ;
7683 while (traversing_index > 0 && bar_height [traversing_index ] < bar_height [traversing_index - 1 ]) {
7784 swap (traversing_index , traversing_index - 1 );
7885 traversing_index --;
7986
80- Thread .sleep (10 );
81- repaint ();
87+ Thread .sleep (10 );// controls the speed
88+ repaint ();// we need it because we ofter replace the contents of a JPanel
8289 }
8390 }
8491 current_index = 0 ;
@@ -182,15 +189,16 @@ public Void doInBackground() throws InterruptedException {
182189 randow_index = new Random ().nextInt (getSIZE ());
183190 swap (j , randow_index );
184191
185- Thread .sleep (20 );
186- repaint ();
192+ Thread .sleep (10 ); // controls the speed
193+ repaint ();// we need it because we ofter replace the contents of a JPanel
187194 }
188195 return null ;
189196 }
197+ // after finishing the process
190198 @ Override
191199 public void done () {
192200 super .done ();
193- sorter .execute ();
201+ sorter .execute ();
194202 }
195203 };
196204 shuffler .execute ();
0 commit comments