Subversion Repositories programming

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
51 irasnyd 1
// Written by Ira Snyder
2
 
3
import java.io.*;
4
 
5
public class Test {
6
    private int compCount, swapCount;
7
 
8
    private class Entry {
9
        public int x;
10
 
11
        public Entry( int x ) { this.x = x; }
12
 
13
        public boolean compareTo( Entry y ) {
14
            compCount++;
15
 
16
            //this is the only way to do this in java
17
            //java _requires_ a boolean in if() statements
18
            int temp = this.x - y.x;
19
 
20
            if( temp > 0 ) { return true; } // this > y
21
            return false; // this <= y
22
        }
23
 
24
        public Entry setEntry( int x ) {
25
            return new Entry(x);
26
        }
27
 
28
        //this is the only way a swap method can be made in java.
29
        //the usual C++ (and others) way of using pointers is not
30
        //possible in java. (I've come up with a very solid
31
        //explanation of this. See me if you want to know.)
32
        public void swap( Entry[] array, int posA, int posB ) {
33
            Entry temp = array[posB];  // temp = B
34
            array[posB] = array[posA]; // B = A
35
            array[posA] = temp;        // A = temp
36
            swapCount++;
37
        }
38
 
39
        public String toString() { return Integer.toString(x); }
40
 
41
    } //end Entry class
42
 
43
    public int getCompCount() { return compCount; }
44
    public int getSwapCount() { return swapCount; }
45
 
46
    public void resetCompCount() { compCount = 0; }
47
    public void resetSwapCount() { swapCount = 0; }
48
 
49
 
50
    public void testBubbleSort() {
51
        Entry[] array = { new Entry(3), new Entry(2), new Entry(1) };
52
 
53
        for( int i=0; i<array.length; i++ ) { System.out.print(array[i] + ", "); }
54
        System.out.println();
55
 
56
        array = BubbleSort(array);
57
 
58
        for( int i=0; i<array.length; i++ ) { System.out.print(array[i] + ", "); }
59
        System.out.println();
60
    }
61
 
62
    public Entry[] BubbleSort( Entry[] a ) {
63
        for( int i=a.length-1; i>0; i-- )
64
            for( int j=0; j<i; j++ )
65
                if( a[j].compareTo(a[j+1]) ) a[j].swap(a,j,j+1);
66
 
67
        return a;
68
    }
69
 
70
}
71