
public class SelectionSort {

    static int cnt = 0;
    static int N = 20;
    static double a[] = new double[N];

    static void exch(double[] a, int i, int j){
        double t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    //selection sort
    //first, find the smallest element, and exchange it with
    //the element in the first position.
    //Then, find the second smallest ...

    static void selection(double[] a, int l, int r){
        for (int i = l; i < r; i++){
            int min = i;
            for (int j = i+1; j <= r; j++){
                cnt++;
                if (a[j] < a[min])
                    min = j;
            }
            exch(a, i, min);
        }
    }

    public static void main (String[] args){
        for(int i = 0; i < N; i++)
            a[i] = Math.random();
        selection(a, 0, N-1);
        if( N < 100 )
            for(int i = 0; i < N; i++)
                System.out.println(a[i] + " ");
        System.out.println("Compares used: " + cnt);
    }
}
