Java 选择排序算法

选择排序算法

package sort;

import util.BaseUtil;

public class SelectSort {
    public static int[] sortAsc(int[] array) {
        if (0 == array.length) {
            return array;
        }

        for (int i = 0; i < array.length - 1; i++) {
            int min = array[i];
            int minIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < min) {
                    minIndex = j;
                    min = array[j];
                }
            }

            if (i != minIndex) {
                array[minIndex] = array[i];
                array[i] = min;
            }
        }

        return array;
    }

    public static int[] sortAscDebug(int[] array) {
        if (0 == array.length) {
            return array;
        }

        System.out.print("原数组: ");
        BaseUtil.arrayIntPrint(array);

        // 只需要length - 1趟,即可有序
        for (int i = 0; i < array.length - 1; i++) {
            int min = array[i];
            int minIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < min) {
                    minIndex = j;
                    min = array[j];
                }
            }

            if (i != minIndex) {
                // 交换写错了,min存放的是找到的最小值
                array[minIndex] = array[i];
                array[i] = min;
            }

            System.out.print("第" + (i + 1) + "趟: ");
            BaseUtil.arrayIntPrint(array);
        }

        return array;
    }
}

 

猜你喜欢

转载自www.cnblogs.com/6xiong/p/13211389.html