在分析中,我设计了三种数据,第一种是a[i] = n - i;也就是最坏的情况。第二种的a[i] = i;这是最好的情况。第三中是a[i] = 一个随机数,也就是平均情况。
这里用了jxl这个包,将得出的数据导入进excel表中,并绘制出图像。
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import jxl.write.Label;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class Test
{
static int num[] = new int[10000];
static Random random = new Random();
public static void main(String[] args) throws IOException, RowsExceededException, WriteException
{
File xlsFile = new File("jxl.xls");
// 创建一个工作簿
WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
// 创建一个工作表
WritableSheet sheet = workbook.createSheet("sheet1", 0);
sheet.addCell(new Label(0, 0, "n"));
sheet.addCell(new Label(0, 1, "最坏情况比较次数"));
sheet.addCell(new Label(0, 2, "最坏情况移动次数"));
sheet.addCell(new Label(0, 3, "平均比较次数"));
sheet.addCell(new Label(0, 4, "平均移动次数"));
sheet.addCell(new Label(0, 5, "最好情况比较次数"));
sheet.addCell(new Label(0, 6, "最好情况移动次数"));
for (Integer i = 0; i < 9; i++)
{
Integer n = (i + 1) * 1000;
sheet.addCell(new Label(i + 1,0,n.toString()));
giveNum((i + 1) * 1000);
try
{
BubbleSort((i + 1) * 1000, 1, i, sheet);
} catch (Exception e)
{
e.printStackTrace();
}
}
for (int i = 0; i < 9; i++)
{
giveRadomNum((i + 1) * 1000);
try
{
BubbleSort((i + 1) * 1000, 2, i, sheet);
} catch (Exception e)
{
e.printStackTrace();
}
}
for (int i = 0; i < 9; i++)
{
giveNum2((i + 1) * 1000);
try
{
BubbleSort((i + 1) * 1000, 3, i, sheet);
} catch (Exception e)
{
e.printStackTrace();
}
}
workbook.write();
workbook.close();
}
private static void giveNum(int n)
{
for (int i = 0; i < n; i++)
{
num[i] = n - i;
}
}
private static void giveRadomNum(int n)
{
for (int i = 0; i < n; i++)
{
num[i] = random.nextInt(100000);
}
}
private static void giveNum2(int n)
{
for (int i = 0; i < n; i++)
{
num[i] = i;
}
}
private static void BubbleSort(int n, int row, int col, WritableSheet sheet) throws Exception
{
Integer count1 = 0, count2 = 0;
int bound, exchange = n - 1;
//当所有数排列完毕后,exchange的值就为0
while (exchange != 0)
{
bound = exchange;
exchange = 0;
for (int j = 0; j < bound; j++)
{
//比较了bound-1次,即比较次数
if (++count1 > 0 && num[j] > num[j + 1])
{
int temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
count2 = count2 + 3;
exchange = j;
}
}
}
sheet.addCell(new Label(col + 1, 2 * row - 1, count1.toString()));
sheet.addCell(new Label(col + 1, 2 * row, count2.toString()));
}
}
由图可知,最坏情况比较次数与平均情况比较次数基本持平,而最好情况比较次数则最低与其他情况相比接近于0,最好情况移动次数必然为0,,因为只进行了一轮排序就跳出了循环,且比较次数与移动次数满足二次函数关系。