五、选择排序

文章目录

原理

每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法

package exercise.array;

import java.util.Arrays;

public class SelectSort {
    void selectSort(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            int minIndex = findMinIndex(i,arr);
            if (minIndex == i){
                continue;
            }
            //最小的和当前的做交换
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }

    /**
     *
     * @param beginIndex 当前开始的寻找的索引
     * @param arr  数组
     * @return 返回从beginIndex开始查找,arr中最小的的数的索引
     */
    int findMinIndex (int beginIndex,int[] arr){
        int min = arr[beginIndex];
        int minIndex = beginIndex;
        for (int i = beginIndex; i <arr.length; i++) {
            if (min>arr[i]){
                min = arr[i];
                minIndex = i;
            }
        }
        return minIndex;
    }


    void print(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+"\t");
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{7,5,1,2,4,6,10};
        SelectSort selectSort = new SelectSort();
        selectSort.selectSort(arr);
        selectSort.print(arr);
    }
}

input:

7,5,1,2,4,6,10

output:

1	2	4	5	6	7	10	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值