Java - 查找排序

 个人理解:
     每次找到当前查找数组的最小值,并替换位置

package com.example;

import java.util.Arrays;

public class SelectionSort {

    private static void sort(int [] array){
        System.out.println("遍历前: " + Arrays.toString(array));
        for (int i = 0; i < array.length; i++) {
            // 因为每一次循环, 都会把当前最小的值放在前面, 所以最小值的下标从循环下标开始
            int currentMinIndex = i;
            int currentMinNumber = array[i];
            System.out.println("判断前, index = " + i + "\t currentMinNumber = " + currentMinNumber);
            // j = i + 1 是因为当前最小的值已经是array[i]当前下标对应的值了, 所以要进行判断的话只需要验证后面的即可。
            for (int j = i + 1; j < array.length; j++) {
                // 当 当前最小值大于当前值时, 需要替换最小值与最小值目前下标
                if(currentMinNumber > array[j]){
                    currentMinNumber = array[j];
                    currentMinIndex = j;
                }
            }
            System.out.println("判断后, index = " + currentMinIndex + "\t currentMinNumber = " + currentMinNumber);
            // 如果index值发生改变,说明存在比当前数值还小的值。
            // 先将找到的最小值的位置换成当前值, 然后将当前值的位置替换成当前最小值
            if(currentMinIndex != i){
                array[currentMinIndex] = array[i];
                array[i] = currentMinNumber;
            }
            System.out.println(Arrays.toString(array));
        }
        System.out.println("遍历后: " + Arrays.toString(array));

    }

    public static void main(String[] args) {
        int [] array = {999, 55, 88, 99, 5, 8888, 57};
        sort(array);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值