package sort;
public interface Compare {
boolean compareTo ( int a, int b) ;
}
package sort;
public class ArraySortUtil {
public static int [ ] bubbleSort ( int [ ] a, Compare c) {
for ( int i = 0 ; i < a. length; i++ ) {
for ( int j = 0 ; j < a. length - i - 1 ; j++ ) {
if ( c. compareTo ( a[ j] , a[ j + 1 ] ) ) {
int t = a[ j] ;
a[ j] = a[ j + 1 ] ;
a[ j + 1 ] = t;
}
}
}
return a;
}
public static int [ ] selectSort ( int [ ] a, Compare c) {
for ( int i = 0 ; i < a. length; i++ ) {
int k = i;
for ( int j = i + 1 ; j < a. length; j++ ) {
if ( c. compareTo ( a[ k] , a[ j] ) ) {
k = j;
}
}
if ( k != i) {
int t = a[ i] ;
a[ i] = a[ k] ;
a[ k] = t;
}
}
return a;
}
public static int [ ] insertSort ( int [ ] a, Compare c) {
int [ ] b = new int [ a. length + 1 ] ;
for ( int i = 0 ; i < a. length; i++ ) {
int j = i - 1 ;
while ( j > 0 && c. compareTo ( b[ j] , a[ i] ) ) {
b[ j + 1 ] = b[ j] ;
j-- ;
}
b[ j + 1 ] = a[ i] ;
}
return b;
}
public static int [ ] bucketSort ( int [ ] a, Compare c) {
int max = Integer. MIN_VALUE;
for ( int num : a) {
max = Math. max ( num, max) ;
}
int [ ] bucket = new int [ max + 1 ] ;
for ( int i = 0 ; i < a. length; i++ ) {
bucket[ a[ i] ] ++ ;
}
int [ ] b = new int [ a. length] ;
if ( c. compareTo ( 1 , 2 ) ) {
int pos = 0 ;
for ( int i = max; i >= 0 ; i-- ) {
if ( bucket[ i] > 0 ) {
while ( bucket[ i] > 0 ) {
b[ pos++ ] = i;
bucket[ i] -- ;
}
}
}
} else {
int pos = 0 ;
for ( int i = 0 ; i <= max; i++ ) {
if ( bucket[ i] > 0 ) {
while ( bucket[ i] > 0 ) {
b[ pos++ ] = i;
bucket[ i] -- ;
}
}
}
}
return b;
}
}
package sort;
public class LargeToSmall implements Compare {
@Override
public boolean compareTo ( int a, int b) {
if ( a < b) {
return true ;
}
return false ;
}
}
package sort;
public class SmallToLarge implements Compare {
@Override
public boolean compareTo ( int a, int b) {
if ( a > b) {
return true ;
}
return false ;
}
}
package sort;
public class TestSort {
public static void main ( String[ ] args) {
int a[ ] = new int [ ] { 1 , 3 , 2 , 5 , 4 , 8 , 7 , 6 } ;
Compare stl = new SmallToLarge ( ) ;
Compare lts = new LargeToSmall ( ) ;
System. out. print ( "Sort before:" ) ;
for ( int num : a) {
System. out. print ( num + " " ) ;
}
System. out. println ( "\n" ) ;
a = ArraySortUtil. bucketSort ( a, stl) ;
System. out. print ( "Sorted after:" ) ;
for ( int num : a) {
System. out. print ( num + " " ) ;
}
System. out. println ( ) ;
}
}