排序算法-选择排序(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 分钟前
第2讲:一致性哈希——数据分片与负载均衡
算法·哈希算法
君顾13 分钟前
代驾跑腿业务系统实战开发指南
java·开发语言·代驾跑腿
阿维的博客日记22 分钟前
保姆级教程介绍分词算法BPE
人工智能·算法·分词算法·bpe
Tongzhi20261 小时前
通芝科技无感考勤一体机:软硬一体,开箱即用
数据结构·数据库·科技·算法·均值算法·数据库开发
NGINX开源社区1 小时前
NGINX Ingress Controller 5.5:安全性与性能提升,迁移更轻松
java·服务器·nginx
云烟成雨TD1 小时前
Micrometer 系列【25】Spring Boot Actuator | Spring MVC、Spring WebFlux 指标
java·spring boot·micrometer
地平线开发者1 小时前
BEVdet模型解析
算法·自动驾驶
liudashuang20171 小时前
Kafka Producer 隐藏深坑:Sender 线程自阻塞(自死锁)导致 BufferExhaustedException 完整复盘
java·分布式·kafka·linq
风筱1 小时前
Idea的CC GUI插件安装Claude Code SDK失败
java·ide·ai编程
m0_527034331 小时前
异步任务审核系统设计:消息队列、超时重试与失败补偿
java·大数据·开发语言