选择排序

import java.util.Arrays;

public class SelectSort {
    /**
     * 选择排序,选择一个位置,找到该排在这个位置的值,然后交换
     */
    public int[] sort(int[] src) {
        int minIndex;
        for (int i = 0; i < src.length; i++) {
            minIndex = i;

            //找出应该排在该位置的值
            for (int j = i + 1; j < src.length; j++) {
                //这里可以控制升序还是降序,<升序 >降序
                if (src[j] < src[minIndex]) {
                    minIndex = j;
                }
            }

            //交换
            int temp = src[i];
            src[i] = src[minIndex];
            src[minIndex] = temp;
        }
        return src;
    }

    public static void main(String[] args) {
        int[] src = {1, 4, 5, 6, 8, 9, 12, 0, 2};
        SelectSort selectSort = new SelectSort();
        int[] sort = selectSort.sort(src);
        System.out.println(Arrays.toString(sort));
    }
}

通用泛型,选择排序

import java.util.Arrays;

public class SelectSortGeneric {
    public <T extends Comparable<T>> T[] sort(T[] src) {
        int minIndex;
        for (int i = 0; i < src.length; i++) {
            minIndex = i;
            for (int j = i + 1; j < src.length; j++) {
                if (src[j].compareTo(src[minIndex]) < 0) {
                    minIndex = j;
                }
            }

            if (minIndex == i) {
                continue;
            }

            T temp = src[i];
            src[i] = src[minIndex];
            src[minIndex] = temp;
        }
        return src;
    }


    public static void main(String[] args) {
        Integer[] src = {1, 4, 5, 6, 8, 9, 12, 0, 2};
        SelectSortGeneric selectSort = new SelectSortGeneric();
        Integer[] sort = selectSort.sort(src);
        System.out.println(Arrays.toString(sort));
    }
}