Skip to content

Commit 370db08

Browse files
committed
Added comments and removed some non-DRY code
1 parent bdb773f commit 370db08

File tree

3 files changed

+142
-110
lines changed

3 files changed

+142
-110
lines changed

src/com/example/algorithmvisualizer/AlgVisualizer.java

Lines changed: 49 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,12 @@
1515

1616
import java.util.*;
1717
import javax.swing.*;
18-
import javax.swing.event.ChangeEvent;
19-
import javax.swing.event.ChangeListener;
20-
2118
import java.awt.event.*;
19+
import javax.swing.event.*;
2220

2321
public class AlgVisualizer implements ActionListener, ChangeListener {
2422

25-
private final int FPS_MIN = 2;
23+
private final int FPS_MIN = 2;
2624
private final int FPS_INIT = 10;
2725
private final int FPS_MAX = 100;
2826
private String[] sizeOptions = { "10", "50", "100", "300", "450", "900" }; // array size options
@@ -31,24 +29,28 @@ public class AlgVisualizer implements ActionListener, ChangeListener {
3129
private int delay;
3230
private long totalDelay;
3331
private Integer indexComparisons;
34-
private long startTime; // start time of a sort
32+
private long startTime; // start time of a sort
3533
private long visualizationTime;
3634
private long sortingTime;
3735
private boolean doBubbleSort;
3836
private boolean doInsertionSort;
3937
private boolean doSelectionSort;
4038
private boolean doMergeSort;
4139
private boolean doQuickSort;
42-
private boolean stopSort; // True if sorting is stopped
43-
private Integer[] arr; // array that is going to be sorted
40+
private boolean stopSort; // True if sorting is stopped
41+
private Integer[] arr; // array that is going to be sorted
4442
private ContentWindow frame;
4543
private SwingWorker<Void, Integer[]> arrSort;
4644

4745

4846
/*
49-
* When an action is performed on a component on the JFrame that has had this
47+
* actionPerformed(ActionEvent event)
48+
*
49+
* When an action is performed on a component on the JFrame that has had this
5050
* classes actionListener added to it, this method will decide what to do based
51-
* on what component was clicked on. When a sorting button is clicked, its
51+
* on the event.
52+
*
53+
* When a sorting button is clicked, its
5254
* respective boolean do(..)Sort will be set to true, and arrSort().execute.
5355
* This will call the doInBackground() method in the arrSort object, where it
5456
* will use the do(..)Sort variable to discover which sorting algorithm to use,
@@ -62,7 +64,9 @@ public void actionPerformed(ActionEvent event) {
6264
doInsertionSort = false;
6365
doMergeSort = false;
6466
doQuickSort = false;
67+
6568
// Find the source of the action
69+
// Is there a better way to do this?
6670
if (event.getSource() == frame.getBubbleButton()) {
6771
doBubbleSort = true;
6872
arrSort.execute();
@@ -91,6 +95,15 @@ public void actionPerformed(ActionEvent event) {
9195
}
9296
}
9397

98+
/*
99+
* stateChanged(ChangeEvent e)
100+
*
101+
* This method is called when the FPS slider
102+
* is shifted to change the FPS of sorting.
103+
*
104+
* We change the amount of delay occuring in the
105+
* sorting to what the value of the slider was moved to.
106+
*/
94107
@Override
95108
public void stateChanged(ChangeEvent e) {
96109
JSlider source = (JSlider) e.getSource();
@@ -99,10 +112,13 @@ public void stateChanged(ChangeEvent e) {
99112
setDelay(delay);
100113
}
101114

102-
/*
115+
/*
116+
* reset()
117+
*
103118
* Reset method is called whenever the user presses the reset button, or when a
104-
* new size of array is chosen from the size changer. This method stops sorting,
105-
* re-shuffles the array, clears all swapped indexes, frames painted, tracked
119+
* new size of array is chosen from the size changer.
120+
*
121+
* This method stops sorting, re-shuffles the array, clears all swapped indexes, frames painted, tracked
106122
* time, and comparisons. It must also reset the swingWorker so that the user is
107123
* able to see another sort. Since sort.execute() can only be called once for
108124
* SwingWorker, we simply re-instantiate it so that we are able to call it
@@ -149,28 +165,38 @@ public Integer[] fillArr(Integer[] arr) {
149165
}
150166

151167
/*
152-
* updatePerformance will be called every time the array is repainted. This
153-
* makes it slower / not real time when there is a high delay.
168+
* updatePerformance()
169+
*
170+
* This method will be called every time that the frame is updated in order to
171+
* update our performance statistics.
154172
*
155-
* We get the values for each performance statistic we want to track (number of
156-
* swaps, number of comparisons, visualization time, sorting time), format them
173+
* Finds the values for each performance statistic being tracked (number of
174+
* swaps, number of comparisons, visualization time, sorting time), formats them
157175
* into a string that will then be assigned to the JLabel's text.
158176
*
159177
* frame.pack() makes sure that our new text will fit in the frame, and will
160178
* adjust if it does not.
161179
*/
162180
public void updatePerformance() {
163181
numSwaps = frame.getArrDisplay().getSwappedIndexes().size();
164-
if (!getSort().equals("Not Sorting") && frame.getArrDisplay().getNumChunks() == 0) {
165-
visualizationTime = System.currentTimeMillis() - startTime;
166-
sortingTime = visualizationTime - totalDelay;
167-
} else if (frame.getArrDisplay().getNumChunks() > 1 && !frame.getArrDisplay().isComplete()) {
168-
visualizationTime = System.currentTimeMillis() - startTime;
169-
sortingTime = visualizationTime - totalDelay;
170-
}
182+
183+
// updates the sorting times based on whether or not we are currently visualizing a sort
184+
if (!getSort().equals("Not Sorting") && frame.getArrDisplay().getNumChunks() == 0) {
185+
186+
visualizationTime = System.currentTimeMillis() - startTime;
187+
sortingTime = visualizationTime - totalDelay;
188+
189+
} else if (frame.getArrDisplay().getNumChunks() > 1 && !frame.getArrDisplay().isComplete()) {
190+
191+
visualizationTime = System.currentTimeMillis() - startTime;
192+
sortingTime = visualizationTime - totalDelay; // visualizationTime < totalDelay makes negative time
193+
194+
}
195+
171196
if (stopSort) {
172197
resetTime();
173198
}
199+
174200
String performance = String.format(
175201
"Index Comparisons : %d Index Swaps : %d Visualization Time : %dms Sorting Time : %dms",
176202
indexComparisons, numSwaps, visualizationTime, sortingTime);

src/com/example/algorithmvisualizer/ArrSorting.java

Lines changed: 68 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,9 @@ protected void process(List<Integer[]> chunks) {
9696
private void sleep() {
9797
try {
9898
Thread.sleep(algVisualizer.getDelay());
99-
if (!algVisualizer.stopSort())
100-
algVisualizer.setTotalDelay(algVisualizer.getTotalDelay() + algVisualizer.getDelay());
99+
if (!algVisualizer.stopSort()) {
100+
algVisualizer.setTotalDelay(algVisualizer.getTotalDelay() + algVisualizer.getDelay());
101+
}
101102
} catch (InterruptedException e) {
102103
e.printStackTrace();
103104
}
@@ -222,66 +223,80 @@ private void mergeSort(int l, int r) {
222223
}
223224
}
224225

225-
// Merges two subarrays of arr[].
226-
// First subarray is arr[l..m]
227-
// Second subarray is arr[m+1..r]
228226
private void merge(int l, int m, int r) {
229227
if (algVisualizer.getSort().equals("Merge Sort") && !algVisualizer.stopSort()) { // Needed because of recursion
230-
// Find sizes of two subarrays to be merged
231-
int n1 = m - l + 1;
228+
229+
int n1 = m - l + 1;
232230
int n2 = r - m;
233-
// Create temp arrays
234-
int L[] = new int[n1];
231+
232+
int L[] = new int[n1];
235233
int R[] = new int[n2];
236-
// Copy data to temp arrays
237-
for (int i = 0; i < n1; ++i)
234+
235+
for (int i = 0; i < n1; ++i) {
238236
L[i] = arr[l + i];
239-
for (int j = 0; j < n2; ++j)
237+
}
238+
for (int j = 0; j < n2; ++j) {
240239
R[j] = arr[m + 1 + j];
241-
// Merge the temp arrays
242-
// Initial indexes of first and second subarrays
240+
}
241+
243242
int i = 0, j = 0;
244-
// Initial index of merged subarray array
245243
int k = l;
246244
while (i < n1 && j < n2) {
247-
if (algVisualizer.stopSort())
245+
246+
if (algVisualizer.stopSort()) { // necessary to check this within every loop?
248247
break;
248+
}
249+
249250
algVisualizer.setIndexComparisons(algVisualizer.getIndexComparisons() + 1);
250-
if (L[i] <= R[j]) {
251+
252+
if (L[i] <= R[j]) {
251253
arr[k] = L[i];
252254
i++;
253-
arrDisplay.addSwappedIndexes(k, k + i);
255+
256+
arrDisplay.addSwappedIndexes(k, k + i);
254257
publish(arr.clone());
255258
sleep();
256-
} else {
259+
260+
} else {
257261
arr[k] = R[j];
258262
j++;
259-
arrDisplay.addSwappedIndexes(k, k + j);
263+
264+
arrDisplay.addSwappedIndexes(k, k + j);
260265
publish(arr.clone());
261266
sleep();
262-
}
267+
}
263268
k++;
264269
}
265-
/* Copy remaining elements of L[] if any */
266-
while (i < n1) {
267-
if (algVisualizer.stopSort())
270+
271+
while (i < n1) {
272+
273+
if (algVisualizer.stopSort()) {
268274
break;
275+
}
276+
269277
arr[k] = L[i];
270-
arrDisplay.addSwappedIndexes(k, k + i);
278+
279+
arrDisplay.addSwappedIndexes(k, k + i);
271280
publish(arr.clone());
272281
sleep();
273-
i++;
282+
283+
i++;
274284
k++;
275285
}
276-
/* Copy remaining elements of R[] if any */
277-
while (j < n2) {
278-
if (algVisualizer.stopSort())
286+
287+
while (j < n2) {
288+
289+
if (algVisualizer.stopSort()) {
279290
break;
291+
}
292+
280293
arr[k] = R[j];
281-
arrDisplay.addSwappedIndexes(k, k + j);
294+
295+
arrDisplay.addSwappedIndexes(k, k + j);
282296
publish(arr.clone());
283297
sleep();
284-
j++;
298+
299+
j++;
285300
k++;
286301
}
287302
}
@@ -290,42 +305,45 @@ private void merge(int l, int m, int r) {
290305
private void quickSort(int low, int high) {
291306
if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) { // Needed because of recursion
292307
if (low < high) {
293-
// pi is partitioning index, arr[pi] is now at right place
294-
int pi = partition(low, high);
308+
309+
int pi = partition(low, high);
295310

296-
// Recursively sort elements before
297-
// partition and after partition
298311
quickSort(low, pi - 1);
299312
quickSort(pi + 1, high);
300313
}
301314
if (isSorted() && !algVisualizer.stopSort()) {
302-
arrDisplay.setComplete(true);
303-
publish(arr.clone());
315+
arrDisplay.setComplete(true);
316+
publish(arr.clone());
304317
sleep();
305318
}
306319
}
307320
}
308-
321+
322+
// quicksort
309323
private int partition(int low, int high) {
310324
if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) { // Needed because of recursion
311-
int pivot = arr[high];
312-
int i = (low - 1); // index of smaller element
313-
for (int j = low; j < high; j++) {
314-
if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) {
325+
326+
int pivot = arr[high];
327+
int i = (low - 1);
328+
329+
for (int j = low; j < high; j++) {
330+
331+
if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) {
315332
algVisualizer.setIndexComparisons(algVisualizer.getIndexComparisons() + 1);
316-
// If current element is smaller than the pivot
317-
if (arr[j] < pivot) {
333+
334+
if (arr[j] < pivot) {
318335
i++;
319-
// swap arr[i] and arr[j]
320336
int temp = arr[i];
321337
arr[i] = arr[j];
322338
arr[j] = temp;
323-
arrDisplay.addSwappedIndexes(i, j);
339+
340+
arrDisplay.addSwappedIndexes(i, j);
324341
publish(arr.clone());
325342
sleep();
326343
}
327344
}
328345
}
346+
329347
if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) {
330348
// swap arr[i+1] and arr[high] (or pivot)
331349
int temp = arr[i + 1];
@@ -346,9 +364,11 @@ private int partition(int low, int high) {
346364
*/
347365
private boolean isSorted() {
348366
boolean isSorted = true;
349-
for (int i = 0; i < arr.length - 1; i++) {
350-
if (arr[i] > arr[i + 1])
367+
368+
for (int i = 0; i < arr.length - 1; i++) {
369+
if (arr[i] > arr[i + 1]) {
351370
isSorted = false;
371+
}
352372
}
353373
return isSorted;
354374
}

0 commit comments

Comments
 (0)