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

相关推荐
HAPPY酷几秒前
std::pair` 与 `std::map` 基础
开发语言·c++·算法
heimeiyingwang3 分钟前
官网知识库结构化整理指南
java·sql·架构·database
山东布谷网络科技6 分钟前
对标Yalla和Chamet:海外直播语聊APP中多人派对房的关键技术细节
java·开发语言·人工智能·php·语音识别·软件需求·海外电商系统开发
、BeYourself13 分钟前
Spring AI 文档切片策略优化指南
java·人工智能·spring
喜欢吃燃面13 分钟前
基础算法:高精度
开发语言·c++·学习·算法
xuxie9915 分钟前
【无标题】
java·开发语言
堕27415 分钟前
java数据结构当中的《Lambda表达式》
java·数据结构·python
摇滚侠18 分钟前
基于 session 的登录认证方式,基于 token 的登录认证方式,对比
java·开发语言·intellij-idea
北国13718 分钟前
【Java】多线程输出滞后/错误解决&&线程创建方式与原理
java·开发语言
假客套18 分钟前
2026 JAVA 腾讯云人脸比对工具类,支持url或者base64进行比对
java·spring boot·腾讯云人脸比对