zoukankan      html  css  js  c++  java
  • 每天学点java_选择排序

    package com.czj;
    
    public class SelectSort {
        /**
         * 选择排序,对sortArray传入的数组进行从小到大排序。
         * 思路就是   找到数组中最小的值,放到数组第一个位置,然后找到第二个最小值,放到第二个位置
         * @param sortArray
         */
        public void selectSort(int[] sortArray){
            int last=sortArray.length; //last为数组长度
            for(int i=0;i<last;i++){ //遍历循环数组
                int currentMin=sortArray[i];//设定数组第一个为最小值
                int currentMinIndex=i;//记录下标
                
                //找出比设定的最小值更小的值,记录值和下标
                for(int j=i;j<last;j++){
                    if(currentMin>sortArray[j]){//这里换成大于号可以让数组从大到小排列
                        currentMin=sortArray[j];
                        currentMinIndex=j;
                    }
                }
                //进行交换,把最小的值换到最前面,
                if(currentMinIndex!=i){
                    sortArray[currentMinIndex]=sortArray[i];
                    sortArray[i]=currentMin;
                }
            }
        }
        
        public static void main(String[] args) {
            int[] sortNum={1,5,2,7,4,9,345,234};
            SelectSort selectSort=new SelectSort();
            selectSort.selectSort(sortNum);
            for(int i:sortNum){
                System.out.print(i+",");
            }
        }
        
    
    }

     选择排序的时间复杂度为O(n^2) .

    选择排序不稳定,为什么说不稳定了?

    其实不稳定指相对位置:比如    5    5   2   3   6

    选择排序后: 2    3    5   5   6  

    咋一看好像没有问题, 其实第一个5的位置相对于第二个5的位置发生了改变,

    5(1)    5(2)   2   3   6

    2   3   5(2)    5(1)    6

    所以说它不稳定。指的就是这种相对位置的改变。     

  • 相关阅读:
    C#带日期型默认值参数的函数
    mvc调用webapi上传图片或文件
    mysql增删改查存储过程
    sql 分页存储过程
    sql 出库存储过程
    Ternura
    留言板
    友链
    .net 死锁
    C#微信小程序搜索框
  • 原文地址:https://www.cnblogs.com/JohnChen-happy/p/4551285.html
Copyright © 2011-2022 走看看