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 {
53 irasnyd 6
    private static int compCount, swapCount;
51 irasnyd 7
 
53 irasnyd 8
    private class Entry implements Comparable {
51 irasnyd 9
        public int x;
10
 
11
        public Entry( int x ) { this.x = x; }
12
 
53 irasnyd 13
        public int compareTo( Object o ) {
51 irasnyd 14
            compCount++;
53 irasnyd 15
            if( !(o instanceof Entry) ) throw new IllegalArgumentException();
16
 
17
            Entry y = (Entry)o;
18
            return this.x - y.x;
51 irasnyd 19
        }
20
 
21
        public Entry setEntry( int x ) {
22
            return new Entry(x);
23
        }
24
 
25
        public String toString() { return Integer.toString(x); }
26
 
27
    } //end Entry class
28
 
29
    public int getCompCount() { return compCount; }
30
    public int getSwapCount() { return swapCount; }
31
 
32
    public void resetCompCount() { compCount = 0; }
33
    public void resetSwapCount() { swapCount = 0; }
34
 
53 irasnyd 35
    //this is the only way a swap method can be made in java.
36
    //the usual C++ (and others) way of using pointers is not
37
    //possible in java. (I've come up with a very solid
38
    //explanation of this. See me if you want to know.)
39
    public static void swap( Object[] array, int posA, int posB ) {
40
        Object temp = array[posB];  // temp = B
41
        array[posB] = array[posA]; // B = A
42
        array[posA] = temp;        // A = temp
43
        swapCount++;
44
    }
51 irasnyd 45
 
53 irasnyd 46
    public void printArray( Object[] array, PrintStream ps ) {
47
        int i=0;
48
        for( i=0; i<array.length-1; i++ ) { System.out.print(array[i] + ", "); }
49
        System.out.println(array[i]); //print the last element
50
    }
51
 
51 irasnyd 52
    public void testBubbleSort() {
53 irasnyd 53
        Entry[] array = { new Entry(3), new Entry(2), new Entry(1), new Entry(12), new Entry(812), new Entry(10), new Entry(4) };
51 irasnyd 54
 
53 irasnyd 55
        printArray(array,System.out);
56
        SortMethods.QuickSort(array,0,array.length);
57
        printArray(array,System.out);
51 irasnyd 58
 
53 irasnyd 59
        System.out.println("swapcount: " + getSwapCount());
60
        System.out.println("compcount: " + getCompCount());
51 irasnyd 61
    }
62
 
63
}
64