集册 Java实例教程 实现选择排序

实现选择排序

欢马劈雪     最近更新时间:2020-01-02 10:19:05

440
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
实现选择排序
/**来 自 时 代 J a v a - N o w J a v a . c o m**/


public class Selection {


    public static void sort(Comparable[] a) {

        int N = a.length;

        for (int i = 0; i < N; i++) {

            int min = i;

      

            for (int j = i+1; j < N; j++) {

                if (less(a[j], a[min]))

                    min = j;

            }

            exch(a, i, min);

        }

    }

    /*来自 nowjava.com - 时  代  Java*/

    //check if the first argument is smaller than second

    private static boolean less(Comparable v, Comparable w) {

        return v.compareTo(w) < 0;

    }

    

    //swap elements (i by j)

    private static void exch(Comparable[] a, int i, int j) {

        Comparable swap = a[i];

        a[i] = a[j];

        a[j] = swap;

    }

    

    public static void main(String[] args) {

        Integer[] data = new Integer[] {28, 96, 51, 86, 69, 68, 42, 24
展开阅读全文