Java实现选择排序

发布于 2021-07-29  31 次阅读


选择排序就像家里做菜一样,先把所有的西红柿观察一遍,从中挑出最烂的一个吃掉!

Selection类代码如下:

package com.apesblog.sort.selection;

public class Selection {

    public static void sort(Comparable[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            int min = i;
            for (int j = i + 1; j < a.length; j++) {
                if (greater(a[min], a[j])) {
                    min = j;
                }
            }
            if (i != min) {
                exch(a, i, min);
            }
        }
    }

    private static boolean greater(Comparable i, Comparable j) {
        return i.compareTo(j) > 0;

    }

    private static void exch(Comparable[] a, int i, int j) {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

}

测试类如下:

package com.apesblog.sort.selection;

import java.util.Arrays;

public class Test {

    public static void main(String[] args) {
        Integer[] a = { 4, 5, 6, 3, 2, 1 };
        Selection.sort(a);
        System.out.println("选择排序:" + Arrays.toString(a));
              
        String[] str = { "d", "e", "f", "c", "b", "a" };
        Selection.sort(str);
        System.out.println("选择排序:" + Arrays.toString(str));

    }

}

运行结果如下: