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));
        }
    }
    
  • 相关阅读:
    墙裂推荐!B站上的Python学习资源
    docker实践-安装wordpress
    docker 使用:创建nginx容器
    docker 使用:镜像和容器
    python标准库:ftplib模块
    python标准库:datetime模块
    python标准库:csv 模块
    python标准库-calendar 模块
    python标准库-builtin 模块之compile,execfile
    python标准库-array 模块
  • 原文地址:https://www.cnblogs.com/RealQ/p/14253827.html
Copyright © 2011-2022 走看看