public class Sort extends AlgorithmAnimator
1: import java.awt.*;
2:
3: public class Sort extends AlgorithmAnimator {
4: protected void initAnimator() {
5: setDelay(20);
6: algName = "BubbleSort";
7: String at = getParameter("alg");
8: if (at != null)
9: algName = at;
10: scramble();
11: }
12: protected void scramble() {
13: arr = new int[getSize().height / 2];
14: for (int i = arr.length; --i >= 0;) {
15: arr[i] = i;
16: }
17: for (int i = arr.length; --i >= 0;) {
18: int j = (int)(i * Math.random());
19: swap(arr, i, j);
20: }
21: }
22: private void swap(int a[], int i, int j) {
23: int T;
24: T = a[i]; a[i] = a[j]; a[j] = T;
25: }
26: protected void paintFrame(Graphics g) {
27: Dimension d = getSize();
28: g.setColor(Color.white);
29: g.fillRect(0, 0, d.width, d.height);
30: g.setColor(Color.black);
31: int y = d.height - 1;
32: double f = d.width / (double) arr.length;
33: for (int i = arr.length; --i >= 0; y -= 2)
34: g.drawLine(0, y, (int)(arr[i] * f), y);
35: }
36: protected void bubbleSort(int a[]) {
37: for (int i = a.length; --i >= 0; )
38: for (int j = 0; j < i; j++) {
39: if (a[j] > a[j+1])
40: swap(a, j, j + 1);
41: pause();
42: }
43: }
44: protected void quickSort(int a[], int lo0, int hi0) {
45: int lo = lo0;
46: int hi = hi0;
47: int mid;
48: pause();
49: if (hi0 > lo0) {
50: mid = a[(lo0 + hi0) / 2 ];
51: while(lo <= hi) {
52: while ((lo < hi0) && (a[lo] < mid))
53: ++lo;
54: while ((hi > lo0) && (a[hi] > mid))
55: --hi;
56: if(lo <= hi) {
57: swap(a, lo, hi);
58: pause();
59: ++lo;
60: --hi;
61: }
62: }
63: if(lo0 < hi)
64: quickSort(a, lo0, hi);
65: if(lo < hi0)
66: quickSort(a, lo, hi0);
67: }
68: }
69: protected void algorithm() {
70: if ("BubbleSort".equals(algName))
71: bubbleSort(arr);
72: else if ("QuickSort".equals(algName))
73: quickSort(arr, 0, arr.length - 1);
74: else
75: bubbleSort(arr);
76: }
77:
78: int arr[];
79: String algName;
80:
81: }