Methods Summary |
---|
public void | init()Initialize the applet.
String at = getParameter("alg");
if (at == null) {
at = "BubbleSort";
}
algName = at + "Algorithm";
scramble();
setBackground(Color.white);
setSize(100, 100);
addMouseListener(new MyAdapter());
|
public void | paint(java.awt.Graphics g)Paint the array of numbers as a list
of horizontal lines of varying lenghts.
int[] a = arr;
int y = getSize().height - 1;
// Erase old lines
g.setColor(Color.lightGray);
for (int i = a.length; --i >= 0; y -= 2) {
g.drawLine(arr[i], y, getSize().width, y);
}
// Draw new lines
g.setColor(Color.black);
y = getSize().height - 1;
for (int i = a.length; --i >= 0; y -= 2) {
g.drawLine(0, y, arr[i], y);
}
if (h1 >= 0) {
g.setColor(Color.red);
y = h1 * 2 + 1;
g.drawLine(0, y, getSize().width, y);
}
if (h2 >= 0) {
g.setColor(Color.blue);
y = h2 * 2 + 1;
g.drawLine(0, y, getSize().width, y);
}
|
void | pause()Pause a while.
pause(-1, -1);
|
void | pause(int H1)Pause a while, and draw the high water mark.
pause(H1, -1);
|
void | pause(int H1, int H2)Pause a while, and draw the low&high water marks.
h1 = H1;
h2 = H2;
if (kicker != null) {
repaint();
}
try {Thread.sleep(20);} catch (InterruptedException e){}
|
public void | run()Run the sorting algorithm. This method is
called by class Thread once the sorting algorithm
is started.
try {
if (algorithm == null) {
algorithm = (SortAlgorithm)Class.forName(algName).newInstance();
algorithm.setParent(this);
}
algorithm.init();
algorithm.sort(arr);
} catch(Exception e) {
}
|
void | scramble()Fill the array with random numbers from 0..n-1.
int[] a = new int[getSize().height / 2];
double f = getSize().width / (double) a.length;
for (int i = a.length; --i >= 0;) {
a[i] = (int)(i * f);
}
for (int i = a.length; --i >= 0;) {
int j = (int)(i * Math.random());
int t = a[i];
a[i] = a[j];
a[j] = t;
}
arr = a;
|
private synchronized void | startSort()For a Thread to actually do the sorting. This routine makes
sure we do not simultaneously start several sorts if the user
repeatedly clicks on the sort item. It needs to be
synchronoized with the stop() method because they both
manipulate the common kicker variable.
if (kicker == null || !kicker.isAlive()) {
scramble();
repaint();
kicker = new Thread(this);
kicker.start();
}
|
public synchronized void | stop()Stop the applet. Kill any sorting algorithm that
is still sorting.
if (kicker != null) {
try {
kicker.stop();
} catch (IllegalThreadStateException e) {
// ignore this exception
}
kicker = null;
}
if (algorithm != null){
try {
algorithm.stop();
} catch (IllegalThreadStateException e) {
// ignore this exception
}
}
|
public void | update(java.awt.Graphics g)Update without erasing the background.
paint(g);
|