import java.util.*;

/**
 *  Quick-sort algorithm of <code>double[]</code> arrays.
 *   @author  Josef.Pelikan@mff.cuni.cz
 *   @version 0.007 (2001/06/15)
 *   @since   0.007
 */
public class QuickSortDouble {

    /** Minimal quick-sort array size (shorter segments are sorted by insert-sort). */
    protected static final int QSMIN = 12;

    /**
     *  Sorting routine.
     *   @param  a Array which holds the sorted segment.
     *   @param  from Starting index of the segment.
     *   @param  len Length of the segment.
     */
    public static final void sort ( double[] a, int from, int len )
    {
        int i, j;
        int to = from + len;

        if ( len < QSMIN ) {                // short array => insert-sort
            while ( len > 1 ) {             // find minimum and swap it to a[from]
                double min = a[ j = from ];
                for ( i = from + 1; i < to; i++ )
                    if ( a[i] < min ) {
                        min = a[i];
                        j = i;
                        }
                if ( j != from ) {
                    a[j] = a[from];
                    a[from] = min;
                    }
                from++;
                len--;
                }
            return;
            }

            // the array is long enough for quick-sort:
        double pivot = (a[from] + a[to-1]) * 0.5;
        i = from - 1; j = to;
        do {
            do i++;
            while ( i < to     && a[i] <= pivot );
            do j--;
            while ( j >= from  && a[j] >= pivot );
            if ( j < i ) break;
            double tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
            } while ( true );

            // j < i => sort [from to j] and [i to to-1]:
        if ( j - from + 1 < to - i ) {      // [from to j] first
            if ( j > from ) sort(a,from,j-from+1);
            sort(a,i,to-i);
            }
        else {                              // [i to to-1] first
            if ( to - i > 1 ) sort(a,i,to-i);
            sort(a,from,j-from+1);
            }
    }

}
