2.选择排序

int nums = [2,4,7,3,9,1,0,4];

  • 第一次遍历 开始下标为 0 , 最小值下标为 6 , 将 下标为6 的 与 下标为 0 的数组互换

交换后数组为 : [0,4,7,3,9,1,2,4]

  • 第二次遍历 从 下标为 1 开始往后遍历 , 最小值 下标为 5 , 将下标为 5 的与 下标为 1 的互换

交换后的数组为 : [0,1,7,3,9,4,2,4]

  • 重复以上操作 最终得到

[0,1,2,3,4,4,7,9]


/**
 * 选择排序
 *
 * 思路: 
 * 1.遍历以此数组 , 获取数组中最小值的下标
 * 
 * 2.将最小值的 和遍历的数组的第 i 个位置 交换
 * 
 * 3.重复 1,2操作
 * 
 *
 */
public class SelectionSort {

    public static int[] selectionSortFun(int[] nums){

        if (nums == null || nums.length == 0) {
            throw new IllegalArgumentException("数组为空");
        }

        int length = nums.length;

        for (int i = 0; i < length; i++) {
            int minIndex = i ;

            for (int j = i + 1; j < length; j++) {
                if (nums[minIndex] > nums[j]) {
                    minIndex = j;
                }
            }

            int a = nums[i];
            nums[i] = nums[minIndex];
            nums[minIndex] = a ;

        }

        return nums;

    }

    public static void main(String[] args) {
        int[] nums = RandomBase.random(10, 2, 50);
        System.out.println(Arrays.toString(nums));
        System.out.println(Arrays.toString(selectionSortFun(nums)));
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值