Java选择排序

/**
 * 选择排序
 *
 * @author 小流慢影
 * @date 2023年3月11日
 */
public class SelectionSortDemo {

    public static void main(String[] args) {
        int[] array = {5, 4, 3, 1, 2, 7, 8, 6, 10, 9, 13, 12, 11};
        selectionSort(array);
        System.out.println(Arrays.toString(array));
    }

    /**
     * 选择排序具体方法
     * @param array 数组
     */
    public static void selectionSort(int[] array) {
        /*
         * 选择排序是从第一个位置开始,每一轮将这个位置的数据和之后的所有数据比较,取最小(或者最大)的与其交换,——>
         * -->然后下一个位置重复操作。
         * firstLocation代表要与后面数据比较的位置,既然是位置,由于数组位置从0开始,——>
         * ——>故最大位置为【array.length - 1】,由于firstLocation是与后面数据比较,所以只能小于最大位置,-->
         * -->方便最后一次时,还能与最大位置比较一次。
         */
        for (int firstLocation = 0; firstLocation < array.length - 1; firstLocation++) {
            // 每一轮比较开始时,默认开始位置是最小位置
            int minLocation = firstLocation;
            // 比较位置从开始位置的下一个开始,到数组最大位置【array.length - 1】结束
            for (int compareLocation = firstLocation + 1;
                 compareLocation < array.length; compareLocation++) {
                // 如果比较位置比前面记录的最小位置还要小,则把比较位置记为最小位置
                if (array[compareLocation] < array[minLocation]) {
                    minLocation = compareLocation;
                }
            }
            /*
             * 上面一轮比较下来,最小位置就出来了.然后将最小位置与第一个位置比较,如果最小位置就是第一个位置,-->
             * -->则保持不变,如果比第一个位置大,则与第一个位置进行交换。
             */
            if (minLocation > firstLocation) {
                swap(array, minLocation, firstLocation);
            }
        }
    }

    /**
     * 交换
     *
     * @param array         数组
     * @param minLocation   最小的位置
     * @param firstLocation 第一个位置
     */
    public static void swap(int[] array, int minLocation, int firstLocation) {
        int temp = array[minLocation];
        array[minLocation] = array[firstLocation];
        array[firstLocation] = temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值