排序算法-选择排序(Java)

选择排序

选择排序 (selection sort)的工作原理非常直接:开启一个循环,每轮从未排序区间选择最小的元素,将其放到已排序区间的末尾。

算法原理

排序数组:(2 4 3 1 5 2)

  1. 2 ++4 3 1 5 2++ ):2依次和4 3 1 5 2比较, i f ( 2 > o t h e r ) ⇒ i n d e x = m i n I n d e x if(2>other) ⇒ index=minIndex if(2>other)⇒index=minIndex,比较完后,交换元素位置。
  2. (1 4 ++3 2 5 2++ ):4依次和3 2 5 2比较,同理得到最小元素的index,比较完后,交换元素位置。
  3. (1 2 3 ++4 5 2++ ):3依次和4 5 2比较,同理,交换元素位置。
  4. (1 2 2 4 ++5 3++)
  5. (1 2 2 3 5 ++4++)
  6. (1 2 2 3 4 5

💡Idea

根据上述推导过程,可以使用 f o r for for嵌套循环

  1. 外层用于遍历每个比较的元素
  2. 内层则用于控制剩下的元素区间(下划线)

T ( n ) = O ( n 2 ) T(n)=O(n^2) T(n)=O(n2)

Coding

java 复制代码
public class bubbleSort {
    public static void main(String[] args) {
        int[] nums={1,4,6,4,5};
        bubbleSorted(nums);
        for(int i:nums){
            System.out.println(i);
        }
    }

    /**
     * 冒泡排序
     * @param nums
     */
    public static void bubbleSorted(int[] nums){
       int n= nums.length;
       for(int i=n-1;i>0;i--){

           for(int j=0;j<i;j++){
               if(nums[j]>nums[j+1]){
                   int tmp=nums[j];
                   nums[j]=nums[j+1];
                   nums[j+1]=tmp;   //大的向右边移动
               }
           }
       }
    }
}

更多有趣内容访问https://github.com/TheRainbow5

参考文献

1 https://www.hello-algo.com/chapter_sorting/selection_sort/

相关推荐
木木子221 小时前
# 星座配对深度解析:Select 长列表选择器、矩阵评分算法与数据驱动建议
java·算法·华为·矩阵·harmonyos
摇滚侠1 小时前
云原生 Java 架构师的第一课 K8s+Docker+KubeSphere+DevOps 51-60
java·云原生·kubernetes
折哥的程序人生 · 物流技术专研1 小时前
第4篇:模板方法 vs 策略模式,面试怎么选?
java·设计模式·策略模式·行为型模式·模版方法模式·扩充系列·继承v组合
大鱼>1 小时前
AI+货物追踪:跨境电商包裹追踪系统
人工智能·深度学习·算法·机器学习
大鱼>1 小时前
AI+货物追踪:全链路货物可视化追踪系统
人工智能·深度学习·算法·机器学习
大江东去浪淘尽千古风流人物1 小时前
【SLAM】slam高动态位姿估计全链路拆解
算法·面试·职场和发展·视觉里程计·slam·vio·大疆
想你依然心痛1 小时前
量子计算对嵌入式密码学的挑战与后量子算法准备
算法·密码学·量子计算
hdsoft_huge1 小时前
JDK系列19:JVM全维度调优实战,内存、元空间、线程栈、GC参数压测调优完整方案
java·开发语言·jvm
曹牧1 小时前
Eclipse:SVN 回复
java·svn·eclipse
Jerry5 小时前
LeetCode 28. 找出字符串中第一个匹配项的下标
算法