排序算法-选择排序(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/

相关推荐
金銀銅鐵2 小时前
带您看懂字节码指令(一):一帧里有什么
java·后端·ai编程
专注仿真3 小时前
知识问答模型用到的算法集详解及代码实例
python·算法·代码·大模型训练·控制算法
nice_lcj5203 小时前
【从零理解 Spring AI · 14】RAG 的四个环节:加载、切分、向量化、检索
java·spring boot·embedding·向量数据库·rag·spring ai·ai应用开发
罗西的思考4 小时前
【轻量化复刻大模型 / KIMI K3】AttnRes 模块交互式演示
人工智能·算法·机器学习
学长毕设5 小时前
基于springboot科创竞赛信息平台-附源码
java·spring boot·后端
聪明的笨猪猪6 小时前
Java 工程案例:AI 生成 @Async 异步线程池踩坑
java·经验分享·面试·ai编程
学长毕设6 小时前
基于SpringBoot公务员考试交流平台-附源码
java·spring boot·后端
好悬给我拽开线7 小时前
ZILOT 论文解析
算法
SL_staff8 小时前
私有化低代码:面向强监管行业的可控数字化实践
java·低代码
饮水桶_T8 小时前
JAVA IO流笔记
开发语言·数据结构·算法