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

相关推荐
2601_9620738117 分钟前
Spring全面详解(基础版)
java·后端·spring
谢亮_vipxieliang1 小时前
ValidX分组验证详解:不同场景使用不同验证规则
java·spring boot·后端·spring cloud·eclipse·hibernate
wuminyu2 小时前
深入剖析 Panama Off-heap 的性能损耗与开销
java·linux·c语言·jvm·c++
维克兜率天2 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
pnoker2 小时前
IoT DC3 AI 能力:Agentic Center 的设计与边界
java·人工智能·物联网·大模型·spring ai
xiaoqiMikko2 小时前
一条 CVSS 9.0 的 RCE,advisory 里没写修复版是哪个 —— fastjson 16723 的字段考古
java·安全
程序员贺加贝3 小时前
一次 SaaS ERP 主数据生命周期设计:Policy、PreCheck 与结构化阻断原因
java·后端·架构·saas
AI情绪识别开源3 小时前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang
catino3 小时前
spring-Bean
java·后端·spring
深入云栈3 小时前
Netty 4.2.x 源码深度解析 (十一):EventExecutor 业务线程池 —— 防止 IO 线程阻塞的并发模型
java·后端