-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlgorithmVisualizer.java
More file actions
89 lines (74 loc) · 2.67 KB
/
Copy pathAlgorithmVisualizer.java
File metadata and controls
89 lines (74 loc) · 2.67 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
import javax.swing.*;
import java.awt.*;
public class AlgorithmVisualizer extends JPanel {
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 600;
private static final int BAR_WIDTH = 5;
private static final int DELAY = 10;
private int[] array;
public AlgorithmVisualizer(int[] array) {
this.array = array;
setPreferredSize(new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT));
setBackground(Color.WHITE);
}
public void mergeSort(int[] arr, int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid+1, end);
merge(arr, start, mid, end);
}
}
public void merge(int[] arr, int start, int mid, int end) {
int[] temp = new int[end - start + 1];
int i = start;
int j = mid+1;
int k = 0;
while (i <= mid && j <= end) {
if (arr[i] <= arr[j]) {
temp[k] = arr[i];
i++;
} else {
temp[k] = arr[j];
j++;
}
k++;
}
while (i <= mid) {
temp[k] = arr[i];
i++;
k++;
}
while (j <= end) {
temp[k] = arr[j];
j++;
k++;
}
for (int p = 0; p < temp.length; p++) {
arr[start + p] = temp[p];
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int x = 0;
for (int i : array) {
int height = i * 5; // Scale the height of the bar according to the value of the array element
int y = WINDOW_HEIGHT - height;
g2.fillRect(x, y, BAR_WIDTH, height);
x += BAR_WIDTH;
}
}
public static void main(String[] args) throws InterruptedException {
int[] array = {5, 3, 8, 4, 2, 1, 7, 6,58, 26, 49, 102, 9, 1111, 10};
AlgorithmVisualizer panel = new AlgorithmVisualizer(array);
JFrame frame = new JFrame("Merge Sort Visualization");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
panel.mergeSort(array, 0, array.length-1);
}
}