我正在尝试在数组长度增加时绘制排序算法(插入排序)性能。 x轴:数组长度 y轴:时间(毫秒) 像this之类的东西 有人可以帮帮我吗? 到目前为止我做了什么:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.gantt.XYTaskDataset;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
public class Sorting extends ApplicationFrame implements ActionListener {
private TimeSeries series;
long totalRuntime = 0;
private double lastValue = 100.0;
public Sorting(String title) {
super(title);
this.series = new TimeSeries("Random Data", Millisecond.class);
final JFreeChart chart = createChart();
final ChartPanel chartPanel = new ChartPanel(chart);
final JPanel content = new JPanel(new BorderLayout());
content.add(chartPanel);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 300));
setContentPane(content);
}
private JFreeChart createChart() {
final XYSeries series1 = new XYSeries("Insertion sort");
XYDataset dataset = new XYSeriesCollection(series1);
final JFreeChart result = ChartFactory.createTimeSeriesChart(
"Dynamic Data Demo",
"Time",
"Value",
dataset,
true,
true,
false
);
final XYPlot plot = result.getXYPlot();
ValueAxis axis = plot.getDomainAxis();
axis.setAutoRange(true);
axis.setFixedDimension(lastValue); // 60 seconds
axis = plot.getRangeAxis();
axis.setRange(0.0, 200.0);
return result;
}
public static void sort(Comparable[] a) {
for (int i = 1; i < a.length; ++i) {
int curIndex = i;
while (curIndex > 0 && a[ curIndex].compareTo(a[ curIndex - 1]) < 0) {
Comparable temp = a[ curIndex - 1];
a[ curIndex - 1] = a[ curIndex];
a[ curIndex--] = temp;
}
}
}
public void actionPerformed(final ActionEvent e) {
int maxElems = 1 << 16;
for (int numElems = 64; numElems <= maxElems; numElems *= 2) {
Integer[] A = new Integer[numElems];
// best case - already sorted
for (int i = 0; i < numElems; ++i) {
A[i] = i;
}
long startTime = System.currentTimeMillis();
sort(A);
long endTime = System.currentTimeMillis();
totalRuntime += ((endTime - startTime) / 1000);
//I suppose that method add.series takes arguments
//totalRunTime and A.length, but doesn't work for me
//
//this.series.add(new Millisecond(), this.lastValue);
}
}
public static void main(final String[] args) {
Sorting s = new Sorting("");
s.pack();
s.setVisible(true);
}
}
这是我得到的输出: