zoukankan      html  css  js  c++  java
  • 简单排序--选择排序

    排序原理:

    1.每一次遍历的过程中,都假定第一个索引处的元素是最小值,和其他索引处的值依次进行比较,如果当前索引处的值大于其他某个索引处的值,则假定其他某个索引出的值为最小值,最后可以找到最小值所在的索引

    2.交换第一个索引处和最小值所在的索引处的值

    排序过程:

    例:{1,2,4,5,7,8,9,10}

    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));
        }
    }
    
  • 相关阅读:
    String和StringBuffer相关
    ReactNative 2018了解一下
    发送验证码倒计时效果
    图片实际尺寸大小
    ES6(一)
    组件开发之选项卡-2
    (function(){代码})()自执行函数
    Vue组件学习之三
    Vue下拉菜单实例demo
    窗口大小左右拖动demo
  • 原文地址:https://www.cnblogs.com/RealQ/p/14253827.html
Copyright © 2011-2022 走看看