一直就对排序算法的动画演示比较好奇,又不想看awt。闲来无聊,在读《Algorithms 4th》的时候,发现了一个封装好了的工具库StdDraw,相当好用,顺便就有了冒泡排序的这个动画演示,当然,也可以轻松将其改为其它排序算法的动画演示。StdDraw中也有很多其它有用的工具类,具体可以查看《Algorithms 4th》。
工具类的地址:http://download.csdn.net/download/huolangge/7933457
public class BubbleSortAnimation {
public final static int N = 50; //表示矩形的个数
public static void print(double[] a) {
double x, y, rw, rh;
for (int i = 0; i < N; i++) {
x = 1.0 * i / N;
y = a[i] / 2.0;
rw = 0.5 / N;
rh = a[i] / 2.0;
StdDraw.filledRectangle(x, y, rw, rh); //x, y指的是矩阵对角线交点的坐标,rw是矩形宽度的一半,rh是矩形高度的一半
}
}
public static void main(String[] args){
while (true) { //不停的演示排序动画
double[] a = new double[N];
for (int i = 0; i < N; i++) {
a[i] = Math.random();
}
for (int i = 0; i < N - 1; i++) {
for (int j = 0; j < N - i - 1; j++) {
if (a[j] > a[j + 1]) {
double t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
print(a);
// 其实应该使用StdDraw.show(int t); //单位为毫秒,不过这个方法被deprecated了,
// 只能把里面的三个函数单独写出来运行了
StdDraw.show();
StdDraw.pause(500);//单位为毫秒,表示每画完一个小矩形后停顿的时间,也就是Thread.sleep(..)
StdDraw.enableDoubleBuffering(); //很重要,如果不写,会导致每次画矩形时屏幕闪烁
StdDraw.clear();
}
StdDraw.clear();
}
}
}
下面是一张运行过程中的gif图: