简单排序--选择排序

排序原理:
1.每一次遍历的过程中,都假定第一个索引处的元素是最小值,和其他索引处的值依次进行比较,如果当前索引处的值大于其他某个索引处的值,则假定其他某个索引出的值为最小值,最后可以找到最小值所在的索引
2.交换第一个索引处和最小值所在的索引处的值
排序过程:
例:{4,6,8,7,9,2,10,1}

package com.sort;
/*--------------
 *  Author:Real_Q
 *  Date:2021-01-06
 *  Time:12:29
 *  Description:选择排序
 * {4,6,8,7,9,2,10,1};
---------------*/
public class SelectSort {

    public static void selectSort(Comparable[] comparables) {
        //排序次数 i
        for (int i = 0; i < comparables.length - 1; i++) {
            //比较遍历数组,找到最小数,记录索引 j
            int min = i;
            for (int j = i + 1; j < comparables.length; j++) {
                if (Comparable(comparables[min], comparables[j])) {
                    min = j;
                }
            }
            exchange(comparables, i, min);
        }

    }
    //比较大小
    public static boolean Comparable(Comparable comparable1, Comparable comparable2) {
        return comparable1.compareTo(comparable2) > 0;
    }

    //交换元素
    public static void exchange(Comparable[] comparable, int leftIndex, int rightIndex) {
        Comparable temp;
        temp = comparable[leftIndex];
        comparable[leftIndex] = comparable[rightIndex];
        comparable[rightIndex] = temp;
    }

}

测试类:
import java.util.Arrays;
import static com.sort.SelectSort.selectSort;

public class TestSelect {
    public static void main(String[] args) {
        Integer[] array = {4,6,8,7,9,2,10,1};
        selectSort(array);
        System.out.println(Arrays.toString(array));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值