算法(第四版)选择排序

package suanfa;

import com.algs4.stdlib.StdOut;

/**
 * Created by evan on 16/11/1.
 * name 选择排序
 */
public class Selection {

    public static void main(String[] args){
        Integer[] cpr = {121,3,1,22,44,12,5,6,23,664,22,34};
        sort(cpr);
        for (Integer value:cpr) {

            StdOut.println(value);
        }

    }

    public static void sort(Comparable[] cprList){
        int N = cprList.length;
        for (int i = 0;i < N;i++){
            int min = i;
            for( int j = i+1;j < N;j++){
                if( less( cprList[j],cprList[min] ) ){

                   min = j;
                }
            }
            exch(cprList,i,min);

        }
    }


    public static void exch(Comparable[] a,int b,int c){

        Comparable t = a[b];
        a[b] = a[c];
        a[c] = t;
        return;

    }

    public static Boolean less(Comparable a, Comparable b){

        return a.compareTo(b) < 0;

    }
}

选择最合适的数放到属于它的位置上

你可能感兴趣的:(算法(第四版)选择排序)