冒泡排序的动画显示
自己写的一个动画:显示冒泡排序
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 import javax.swing.Timer; 5 import java.util.*; 6 public class SortAnimation extends JFrame{ 7 JLabel jlbTitle = new JLabel("Selection Sort"); 8 SelectionSort selectionsort; 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 int num[] = {10,4,7,2,3,8,1,9,5,6}; 12 SortAnimation frame = new SortAnimation(num); 13 frame.setTitle("SortAnimation"); 14 frame.setSize(300,300); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setVisible(true); 17 } 18 public SortAnimation(){ 19 20 } 21 public SortAnimation(int num[]){ 22 setLayout(new BorderLayout()); 23 add(jlbTitle, BorderLayout.NORTH); 24 selectionsort = new SelectionSort(num); 25 add(selectionsort, BorderLayout.CENTER); 26 } 27 class SelectionSort extends JPanel{ 28 private int num[]; 29 private int interval = 10; 30 private int i = 0; 31 private int j = 0; 32 public SelectionSort(int num[]){ 33 this.num = num; 34 Timer timer = new Timer(1000, new TimerListener());//每隔一秒进行一次排序 35 timer.start(); 36 } 37 public SelectionSort(){ 38 39 } 40 public void setNum(int num[]){ 41 this.num = num; 42 repaint(); 43 } 44 public void sort(){//冒泡排序,每次只排序一次 45 if(i < num.length ){ 46 if(j < num.length - i -1){ 47 int temp; 48 if(num[j] > num[j+1]){//将最大的往下沉 49 temp = num[j]; 50 num[j] = num[j+1]; 51 num[j+1] = temp; 52 } 53 setNum(num); 54 j++; 55 } 56 else if(j == num.length - i -1){ 57 j=0; 58 i++; 59 } 60 } 61 } 62 protected void paintComponent(Graphics g){ 63 super.paintComponent(g); 64 int width = getWidth(); 65 int height = getHeight(); 66 int interval = 10; 67 int x[] = {0, 0, interval, interval}; 68 int y[] = {height, 0, 0, height}; 69 70 for(int i = 0; i < num.length; i++) 71 { 72 x[0] = i * 2 * interval; 73 x[1] = i * 2 * interval; 74 x[2] = (i * 2 + 1)* interval; 75 x[3] = (i * 2 + 1)* interval; 76 77 y[1] = height - num[i] * 10; 78 y[2] = height - num[i] * 10; 79 g.drawPolyline(x, y, 4); 80 } 81 } 82 class TimerListener implements ActionListener{ 83 public void actionPerformed(ActionEvent e){ 84 sort(); 85 } 86 } 87 } 88 }