-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingAlgorithms.java
More file actions
107 lines (99 loc) · 3.74 KB
/
Copy pathSortingAlgorithms.java
File metadata and controls
107 lines (99 loc) · 3.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import java.util.ArrayList;
import java.util.Collections;
public class SortingAlgorithms {
/**
* Inefficient Bubble Sort Algorithm (does not terminate if no swaps are made)
* @param arr The Array to be sorted.
* @param panel The JPanel where the algorithm is visualized.
*/
public static void visualizeBubbleSort(ArrayList<Integer> arr, RectanglePanel panel) {
Thread t = new Thread(() -> {
try {
for (int i = 0; i < arr.size() - 1; i++) {
for (int j = 0; j < arr.size() - i - 1; j++) {
if (arr.get(j) > arr.get(j + 1)) {
Collections.swap(arr, j, j + 1);
}
panel.setComparisonIndices(j, j + 1);
panel.repaint();
Thread.sleep(50);
}
}
//List Sorted
panel.setComparisonIndices(-1, -1);
panel.repaint();
SortingVisualiserGUI.setButtons(true);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
System.exit(1);
}
});
t.start();
}
/**
* Efficient Bubble Sort Algorithm (terminates if no swaps are made)
* @param arr The Array to be sorted.
* @param panel The JPanel where the algorithm is visualized.
*/
public static void visualizeBubbleSortEfficient(ArrayList<Integer> arr, RectanglePanel panel) {
Thread t = new Thread(() -> {
try {
boolean noSwaps = true;
for (int i = 0; i < arr.size() - 1; i++) {
for (int j = 0; j < arr.size() - i - 1; j++) {
if (arr.get(j) > arr.get(j + 1)) {
Collections.swap(arr, j, j + 1);
noSwaps = false;
}
panel.setComparisonIndices(j, j + 1);
panel.repaint();
Thread.sleep(50);
}
if (noSwaps) {
break;
}
}
//List Sorted
panel.setComparisonIndices(-1, -1);
panel.repaint();
SortingVisualiserGUI.setButtons(true);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
System.exit(1);
}
});
t.start();
}
/**
* Selection Sort Algorithm
* @param arr The Array to be sorted.
* @param panel The JPanel where the algorithm is visualized.
*/
public static void visualizeSelectionSort(ArrayList<Integer> arr, RectanglePanel panel) {
Thread t = new Thread(() -> {
try {
for (int i = arr.size() - 1; i >= 0; i--) {
int maxSoFar = 0;
for (int j = 1; j <= i; j++) {
panel.setComparisonIndices(maxSoFar, j);
panel.repaint();
Thread.sleep(50);
if (arr.get(j) > arr.get(maxSoFar)) {
maxSoFar = j;
}
}
Collections.swap(arr, maxSoFar, i);
panel.setComparisonIndices(-1, -1);
panel.repaint();
Thread.sleep(50);
}
//List Sorted
SortingVisualiserGUI.setButtons(true);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
System.exit(1);
}
});
t.start();
}
}