好的,我想出了如何制作 GUI 类和排序类,但似乎可以弄清楚如何实现可比较的类。我需要创建随机大小的矩形,然后将它们整理出来。再次感谢任何帮助。
import java.util.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoSorts extends Applet implements ActionListener
{
private final int APPLET_WIDTH = 600;
private final int APPLET_HEIGHT = 600;
Button sort;
Label sort_label;
String pr_name;
int[] random = new int[20];
int[] sorter = new int[20];
public void init()
{
sort = new Button("Sort");
add(sort);
sort.addActionListener(this);
sort_label = new Label("Orange Selection / Black Bubble");
add(sort_label);
randomGen(random);
sorter = random;
setBackground (Color.white);
setSize (APPLET_WIDTH, APPLET_HEIGHT);
}
private void randomGen (int...random) {
for (int i = 0; i < 20; i++){
random [i] = (int) (20 +(Math.random()*300-20));
}
}
public void paint(Graphics g)
{
for (int i = 0; i < 20; i++ ){
g.setColor(Color.blue);
g.fillRect((int) (10 + (i*50)), 300, 50, ((random[i])));
g.setColor(Color.black);
g.fillRect((int) (10 + (i*50)), 300, 25, (sorter[i]));
}
g.drawRect (20, 30, 130, 50);
sort.setLocation(0,220);
sort_label.setLocation(0,270);
sort_label.setSize(400,30);
}
public void actionPerformed(ActionEvent e) {
Sorting.selectionSort(random);
Sorting.insertionSort (sort);
repaint();
}
}
这是我的排序课程
import java.awt.event.ActionEvent;
public class Sorting{
public static void selectionSort (Comparable[] list) {
int min;
Comparable temp;
for (int index = 0; index < list.length-1; index++)
{
min = index;
for (int scan = index+1; scan < list.length; scan++)
if (list[scan].compareTo(list[min]) < 0)
min = scan;
temp = list[min];
list[min] = list[index];
list[index] = temp;
}
}
public static void insertionSort (Comparable[] sorter) {
for (int index = 1; index < sorter.length; index ++){
Comparable key = sorter[index];
int position = index;
while (position > 0 && key.compareTo(sorter[position-1]) < 0){
sorter [position] = sorter[position-1];
position--;
}
sorter[position] = key;
}
}
然后这是我的同类课程,我需要一些帮助
public class width implements Comparable {
int[] random = new int[20];
int[] sorter = new int[20];
@Override
public int compareTo(Object o) {
int result = 0;
if(random[1] == sorter[1])
result = random.length;
return result;
}