-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
80 lines (65 loc) · 1.56 KB
/
InsertionSort.java
File metadata and controls
80 lines (65 loc) · 1.56 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
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
/**
* Soham Dessai
*/
import javax.swing.JComponent;
public class InsertionSort {
private int[] array;
private int position = -1;
private int indicated = -1;
private int replaced = -1;
private JComponent component;
private static final int DELAY = 100;
public InsertionSort(int[] exarray, JComponent excomponent) {
this.array = exarray;
this.component = excomponent;
}
//ALgorithim for insertion sort
public void sort() throws InterruptedException {
int n = array.length;
for(int j=1; j<n; j++) {
int key = array[j];
int i = j-1;
position = j;
indicated = j;
try {
while((i>=0) && (array[i] > key)) {
array[i+1] = array[i];
i--;
}
array[i+1] = key;
replaced = (i+1);
} finally {
}
pause(1);
}
}
//Draws rectangles and indicates object that is getting inserted
public void draw(Graphics g) {
g.setColor(Color.BLACK);
g.drawString("Insertion- Algorithm that builds the final sorted array by inserting items one at a time", 50, 300);
try {
for(int i=0; i<array.length; i++) {
if(i == position) {
g.setColor(Color.RED);
} else if(i == replaced) {
g.setColor(Color.ORANGE);
}
else if(i <= indicated) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.BLUE);
}
g.fillRect(100 + (i*10), 350, 8, array[i]*2);
}
} finally {
}
}
//delays the pause
public void pause(int steps) throws InterruptedException {
component.repaint();
Thread.sleep(DELAY * steps);
}
}