Blame | Last modification | View Log | RSS feed
// Written by Ira Snyderimport java.io.*;public class Test {private int compCount, swapCount;private class Entry {public int x;public Entry( int x ) { this.x = x; }public boolean compareTo( Entry y ) {compCount++;//this is the only way to do this in java//java _requires_ a boolean in if() statementsint temp = this.x - y.x;if( temp > 0 ) { return true; } // this > yreturn false; // this <= y}public Entry setEntry( int x ) {return new Entry(x);}//this is the only way a swap method can be made in java.//the usual C++ (and others) way of using pointers is not//possible in java. (I've come up with a very solid//explanation of this. See me if you want to know.)public void swap( Entry[] array, int posA, int posB ) {Entry temp = array[posB]; // temp = Barray[posB] = array[posA]; // B = Aarray[posA] = temp; // A = tempswapCount++;}public String toString() { return Integer.toString(x); }} //end Entry classpublic int getCompCount() { return compCount; }public int getSwapCount() { return swapCount; }public void resetCompCount() { compCount = 0; }public void resetSwapCount() { swapCount = 0; }public void testBubbleSort() {Entry[] array = { new Entry(3), new Entry(2), new Entry(1) };for( int i=0; i<array.length; i++ ) { System.out.print(array[i] + ", "); }System.out.println();array = BubbleSort(array);for( int i=0; i<array.length; i++ ) { System.out.print(array[i] + ", "); }System.out.println();}public Entry[] BubbleSort( Entry[] a ) {for( int i=a.length-1; i>0; i-- )for( int j=0; j<i; j++ )if( a[j].compareTo(a[j+1]) ) a[j].swap(a,j,j+1);return a;}}