-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectionSort.java
92 lines (76 loc) · 1.83 KB
/
SelectionSort.java
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
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JComponent;
/**
*
* @author sohamdessai
*
*/
public class SelectionSort {
private int[] array;
private int position = -1;
private int indicated = -1;
private int minimumpos = -1;
private JComponent component;
private static final int DELAY = 100;
public SelectionSort(int[] exarray, JComponent excomponent) {
array = exarray;
component = excomponent;
}
//finds minimum using helper method
public void sort() throws InterruptedException {
for(int i=0; i<array.length-1; i++) {
int minPos = minimumPosition(i);
try {
int temp = array[i];
array[i] = array[minPos];
array[minPos] = temp;
indicated = i;
} finally {
}
pause(1);
}
}
//recursive helper method to fidn minimum postion
private int minimumPosition(int from) throws InterruptedException {
int stored = from;
minimumpos = stored;
for(int i=from+1; i<array.length; i++) {
try {
if(array[i] < array[stored]) {
stored = i;
minimumpos = i;
}
position = i;
} finally {
}
pause(1);
}
return stored;
}
//Demonstrates minimum position selected in the bar graph,
public void draw(Graphics g) {
g.setColor(Color.BLACK);
g.drawString("Selection- Algorithm that repeatedly finds the minimum element and puts it at the beginning. ", 50, 50);
try {
for(int i=0; i<array.length; i++) {
if(i == position) {
g.setColor(Color.RED);
} else if(i == minimumpos) {
g.setColor(Color.ORANGE);
} else if(i <= position) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.BLUE);
}
g.fillRect(100 + (i*10), 100, 8, array[i]*2);
}
} finally {
}
}
public void pause(int steps) throws InterruptedException {
component.repaint();
Thread.sleep(DELAY * steps);
}
}