Skip to content

Instantly share code, notes, and snippets.

@mmandersheid
Created March 11, 2010 15:38
Show Gist options
  • Save mmandersheid/329247 to your computer and use it in GitHub Desktop.
Save mmandersheid/329247 to your computer and use it in GitHub Desktop.
A sort timer
import java.awt.*;
public class AList
{
private int data[];
private int howMany;
public AList(int length)
{
howMany = length;
if (howMany < 10)
howMany = 10;
data = new int[howMany];
fill();
}
public void fill()
{
for (int x=0; x<howMany; x++)
data[x] = x;
}
public void shuffle()
{
for (int x=howMany - 1; x>0; x--)
{
int spot = random(x);
int temp = data[spot];
data[spot] = data[x];
data[x] = temp;
}
}
private int random(int max)
{
double r = Math.random();
return (int)((max+1) * r);
}
public long timedSort(ASort s)
{
System.gc();
try
{
Thread.currentThread().sleep(500);
}
catch (Throwable t)
{}
long start = (new java.util.Date()).getTime();
s.sort(this);
return (new java.util.Date()).getTime() - start;
}
public int getHowMany()
{
return howMany;
}
public int[] getData()
{
return data;
}
public String toString()
{
String s = "AList [" + howMany + "]";
if (howMany <= 20)
for (int x=0; x<howMany; x++)
s += " " + data[x];
else
{
for (int x=0; x<5; x++)
s += " " + data[x];
s += " ...";
for (int x=howMany-5; x<howMany; x++)
s += " " + data[x];
}
return s;
}
public String toString(FontMetrics metrics, int max)
{
String s;
int showing = 10;
if (howMany <= 20)
{
s = "AList [" + howMany + "]";
for (int x=0; x<howMany; x++)
s += " " + data[x];
}
else do
{
s = "AList [" + commaInt(howMany) + "]";
for (int x=0; x<showing; x++)
s += " " + commaInt(data[x]);
s += " ...";
for (int x=howMany-showing; x<howMany; x++)
s += " " + commaInt(data[x]);
showing--;
}
while (metrics.stringWidth(s) > max);
return s;
}
public static String commaInt(long n)
{
return commaInt(n, 0, ' ');
}
public static String commaInt(long n, int places)
{
return commaInt(n, places, ' ');
}
public static String commaInt(long n, int places, char fill)
{
String s = "" + n;
int xtra = s.length() % 3;
int comma;
if (xtra == 0)
comma = 3;
else
comma = xtra;
while (comma < s.length())
{
s = s.substring(0, comma) + ',' + s.substring(comma);
comma += 4;
}
if (places > 21)
places = 21;
while (s.length() < places)
s = fill + s;
return s;
}
}
public interface ASort
{
public void sort(AList l);
public String getName();
}
public class ASortFactory
{
private static final int NUMBER_OF_SORTS = 4; // increase this number to add a sort
public static ASort[] makeSorts()
{
ASort[] sorts = new ASort[NUMBER_OF_SORTS];
sorts[0] = new BucketSort(); // put a new sort into sorts[1], the next into sorts[2]É
sorts[1] = new BubbleSort();
sorts[2] = new SelectionSort();
sorts[3] = new QuickSort();
return sorts;
}
}
public class BubbleSort implements ASort
{
private int howMany;
private int a[], temp;
public void sort(AList l)
{
howMany = l.getHowMany();
a = l.getData();
temp = 0;
sortIt();
}
public void sortIt(){
for (int i=0; i<howMany-1; i++) {
for (int j=0; j<howMany-1; j++)
if (a[j+1] < a[j]) { /* compare the two neighbors */
temp = a[j]; /* swap a[j] and a[j+1] */
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
public String getName()
{
return "Bubble Sort";
}
}
public class BucketSort implements ASort
{
private int howMany;
private int data[], temp[];
public void sort(AList l)
{
howMany = l.getHowMany();
data = l.getData();
temp = null;
temp = new int[howMany];
sortIt();
}
private void sortIt()
{
for (int x=0; x<howMany; x++)
temp[data[x]] = data[x];
for (int x=0; x<howMany; x++)
data[x] = temp[x];
}
public String getName()
{
return "Bucket Sort";
}
}
import java.awt.*;
import java.awt.event.*;
public class MyPanel extends Panel
{
public static final Font headingFont = new Font("SansSerif", Font.BOLD, 14);
private Label countLabel, sortLabel;
private TextField countField;
private Button[] buttons;
private ASort[] sorts;
private SortCanvas sortCanvas;
public MyPanel()
{
setLayout(null);
setBackground(new Color(200, 225, 255));
// Label and TextField for the number of items to sort
countLabel = new Label("Items to sort");
countLabel.setSize(180,25);
countLabel.setLocation(205, 20);
add(countLabel);
countLabel.setFont(headingFont);
countField = new TextField("1,000");
countField.setSize(100,25);
countField.setLocation(95, 20);
add(countField);
countField.setFont(headingFont);
countField.setBackground(Color.white);
// Label for the sorting methods
sortLabel = new Label("Sorting methods");
sortLabel.setSize(200,25);
sortLabel.setLocation(20, 60);
add(sortLabel);
sortLabel.setFont(headingFont);
// Create the sorts and the array for the buttons
sorts = ASortFactory.makeSorts();
if (sorts == null)
{
System.err.println("Null sort list!");
System.exit(1);
}
buttons = new Button[sorts.length];
// Create the display canvas for the results
sortCanvas = new SortCanvas(countField, buttons, sorts, headingFont);
sortCanvas.setSize(430,130);
sortCanvas.setLocation(10, 160);
add(sortCanvas);
sortCanvas.setBackground(Color.white);
// Create the buttons that start the sorts
for (int n=0; n<sorts.length; n++)
{
if (sorts[n] == null)
{
System.err.println("Sort #" + n + " is null!");
System.exit(1);
}
int row = n / 4;
int col = n % 4;
buttons[n] = new Button(sorts[n].getName());
buttons[n].setSize(90,25);
buttons[n].setLocation(10 + 105*col, 90 + 35*row);
add(buttons[n]);
buttons[n].setBackground(Color.white);
buttons[n].addActionListener(sortCanvas);
}
}
}
/*
applet that runs a panel
*/
import java.awt.*;
import java.applet.Applet;
public class PanelApplet extends Applet
{
Panel panel;
public void init()
{
setLayout(null);
panel = new MyPanel(); // <-- your program name must go here
add(panel);
panel.setSize(getSize().width, getSize().height);
panel.setLocation(0,0);
panel.setVisible(true);
panel.requestFocus();
}
}
public class QuickSort implements ASort
{
private int howMany;
private int list[], temp;
public void sort(AList l)
{
howMany = l.getHowMany();
list = l.getData();
temp = 0;
quickSort(0, howMany-1);
}
public void quickSort(int first, int last){
int i = first, j=last, dividingLine=list[(first+last)/2];
while(i<=j){
while(list[i]<dividingLine)
i++;
while(list[j]>dividingLine)
j--;
if(i<=j){
temp = list[i];
list[i++] = list[j];
list[j--] = temp;
}
}
if(first<j)
quickSort(first,j);
if(i<last)
quickSort(i,last);
}
public String getName()
{
return "Quick Sort";
}
}
public class SelectionSort implements ASort
{
private int howMany;
private int data[];
private int largest, temp, x, y;
public void sort(AList l)
{
howMany = l.getHowMany();
data = l.getData();
temp = 0;
largest = -1;
x = 0;
y = 0;
sortIt();
}
private void sortIt()
{
for(int i = 0; i < (data.length - 1); i++)
{
for(x = 0; x <= (data.length - (i + 1)); x++)
{
if(data[x] > largest)
{
y = x;
largest = data[x];
}
}
temp = data[data.length - (i + 1)];
data[data.length - (i + 1)] = largest;
data[y] = temp;
largest = -1;
}
}
public String getName()
{
return "Selection Sort";
}
}
import java.awt.*;
import java.awt.event.*;
public class SortCanvas extends Canvas implements ActionListener
{
private Font headingFont;
private FontMetrics metrics;
private int width;
private TextField countField;
private Button[] buttons;
private ASort[] sorts;
private long time;
private String name, before, after;
private AList l;
public SortCanvas(TextField countField, Button[] buttons, ASort[] sorts, Font headingFont)
{
this.headingFont = headingFont;
this.countField = countField;
this.buttons = buttons;
this.sorts = sorts;
time = -1;
name = "No Sort";
before = after = "";
l = new AList(1000);
}
public void paint(Graphics g)
{
if (metrics == null)
{
metrics = g.getFontMetrics(g.getFont());
width = getSize().width;
}
if (time < 0)
{
g.setFont(headingFont);
g.drawString("Click on a button to sort.", 50, 50);
}
else
{
g.drawString("Unsorted list: ", 10, 47);
g.drawString(before, 10, 62);
g.drawString("Sorted list: ", 10, 105);
g.drawString(after, 10, 120);
g.setFont(headingFont);
g.drawString("Sorting " + AList.commaInt(l.getHowMany()) + " numbers.", 10, 20);
g.drawString(BL.fixedString((double)time/1000, 3) + " seconds using " + name, 10, 85);
}
}
private void doSort(ASort s)
{
l.shuffle();
before = "" + l.toString(metrics, width - 20);
time = l.timedSort(s);
after = "" + l.toString(metrics, width - 20);
name = s.getName();
repaint();
}
private void setCount()
{
String s = noCommas(countField.getText());
int n = convert(s);
if (n != l.getHowMany())
{
l = null;
l = new AList(n);
}
countField.setText(AList.commaInt(l.getHowMany()));
}
private String noCommas(String s)
{
while (s.indexOf(',') >= 0)
s = s.substring(0, s.indexOf(',')) + s.substring(s.indexOf(',') + 1);
return s;
}
private int convert(String s)
{
int i = 1000;
try
{ i = (new Integer(s)).intValue(); }
catch (Throwable t)
{ }
return i;
}
public void actionPerformed(ActionEvent e)
{
setCount();
for (int n=0; n<sorts.length; n++)
if (e.getSource() == buttons[n])
doSort(sorts[n]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment