import java.util.Comparator; public class MedianQuickSort implements Sort { private Comparator comp = null; public MedianQuickSort( Comparator c ) { comp = c; } public MedianQuickSort() {} public void sort( Object [] d ) { sort( d, 0, d.length - 1 ); } public void sort( Object [] d, int start, int end ) { if ( start >= end ) return; if ( compare( d[ start ], d[ end ] ) > 0 ) exchange( d, start, end ); if ( end - start < 2 ) return; int mid = ( start + end ) / 2; exchange( d, mid, end - 1 ); if ( compare( d[ start ], d[ end - 1 ] ) > 0 ) exchange( d, start, end - 1 ); if ( compare( d[ end - 1 ], d[ end ] ) > 0 ) exchange( d, end - 1, end ); /* * En este punto d[end-1] es el pivote y d[start], d[end-1] y * d[end] ya estñan ordenados, por lo que sólo debemos particionar desde * start+1 hasta end-1. Se asume el caso en que, de principio a fin, se incluyen * menos de tres elementos **/ if ( end - start == 2 ) return; int p = partition( d, start + 1, end - 1 ); sort( d, start, p - 1 ); sort( d, p + 1, end ); } private int partition( Object [] d, int start, int end ) { Object pivot = d[ end ]; int low = start - 1; int high = end; while ( true ) { while ( compare( d[ ++low ], pivot ) < 0 ) ; while ( compare( pivot, d[ --high ] ) < 0 && high > low) ; if ( low >= high ) break; exchange( d, low, high ); } exchange( d, low, end ); return low; } private void exchange( Object [] a, int i, int j ) { // intercambia los elementos low y high del array a Object o = a[ i ]; a[ i ] = a[ j ]; a[ j ] = o; } private int compare( Object a, Object b ) { if ( comp == null ) { return ((Comparable)a).compareTo( b ); } else { return comp.compare( a, b ); } } }