排序动画做了有一段时间了,我觉得有必要记录一下
闲话休提,言归正传
上图
具体就是四个排序动画,分别为插入排序,冒泡排序,选择排序,快速排序
之所以做这个排序动画是因为,以前学习排序,在youtube上看过排序动画视频,很受震撼
后来自己学Java过程渐渐发现这个可以做出来,果然功夫不负有心人总算做出来了
首先这个程序最重要的是以条形图来代表数的大小,数越大,条形图越高
在这里我定义一个类Histogram,主要负责根据数组里的数字,画出条形图来
package Sorting_Animation;
import javax.swing.JPanel;
import java.awt.*;
public class Histogram extends JPanel {
private int[] count;
private int index1; //The index of red bar
private int index2; //The index of red bar
private static final int length = 100;
private int maxCount;
private int begin;
private int end;
/**Set the count and two red bar and display histogram*/
public void showHistogram(int[] count, int index1, int index2){
this.index1 = index1;
this.index2 = index2;
this.count = count;
repaint();
}
/**Set the count and one red bar and display histogram */
public void showHistogram(int[] count, int index1){
this.index1 = index1;
this.count = count;
this.begin = 0;
this.end = count.length;;
repaint();
}
/**Set the count and display histogram */
public void showHistogram(int count[]){
this.count = count;
this.begin = 0;
this.end = count.length;
repaint();
}
/**Show the merge histogram */
public void showMergeHistogram(int count[],int index1,int begin,int end){
this.begin = begin;
this.end = end;
this.count = count;
repaint();
}
/**Define the histogram*/
public Histogram(){
setCount();
setMaxCount(count);
showHistogram(count);
}
public int[] getCount(){
return count;
}
public static int getLength(){
return length;
}
/**Set the random elements*/
public void setCount(){
count = new int[length];
boolean flag=false;
int temp;
int index1 = 0;
while(index1 < length){
temp = (int)(Math.random()*length)+1;
//Check the same element
for(int j=0;j<index1;j++){
if(temp == count[j]){
flag=true;
break;
}
else{
flag = false;
}
}
if(!flag )
count[index1++] = temp;
}
}
/** Set the worst elements */
public void setWorstCount(){
count = new int [length];
while(index1 < length){
count[index1++