直接选择排序

一、排序过程

j从 i + 1 开始,mindIndex 记录值小于 i 下标所对应值的下标,初始值为i

因为 array j < array mindindex 所以把 j 的值赋给mindindex,j++

后续重复这个过程

。。。

然后交换i 与 mindIndex 所对应的值

然后重复上述过程即可

二、代码实现

java 复制代码
    public static void selectSort(int[] arr) {
        for(int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for(int j = i + 1; j < arr.length; j++) {
                if(arr[j] < arr[minIndex]) {
                    mindIndex = j;
                }
            }
            if(minIndex != i) {
                int temp = arr[minIndex];
                arr[minIndex] = arr[i];
                arr[i] = temp;
            }
        }
    }

这个代码的时间复杂度是 O( N^ 2),效率很低

三、另一种写法

思路:定义left 位于最左端,right 位于最右端,一次循环,记录循环中的最大值和最小值,然后更新left 和 right ,再让 left++ ,right--,代码如下:

java 复制代码
    public static void selectSort(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        while(left < right) {
            int minIndex = left;
            int maxIndex = left;
            for(int i = left + 1; i <= right; i++) {
                if(arr[i] < arr[minIndex]) {
                    minIndex = i;
                }
                if(arr[i] > arr[maxIndex]) {
                    maxIndex = i;
                }
            }
            swap(arr,left,minIndex);
            if(maxIndex == left) {
                maxIndex = minIndex;
            }
            swap(arr,maxIndex,right);
            left++;
            right--;
        }
    }
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

为什么要加入maxIndex == left?

有一种情况是left 本身已经指向最大的元素了,然后minIndex 依旧与它交换,然而最大值maxIndex已经确定完毕,right已经修改了,加入这行代码可以解决

当然,时间复杂度仍然是 O( N^ 2)

相关推荐
有点。9 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
午彦琳15 小时前
2026.9.17
数据结构·算法·leetcode
All for pursuit.18 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
彧azz20 小时前
图的最短路径:Dijkstra与Floyd算法
数据结构·笔记·学习
智购科技自动售卖机厂家20 小时前
设备一到夏天就频繁跳闸,从启动电流追到压缩机电容~YH
数据结构·人工智能·python·eclipse
Logic10121 小时前
C语言/数据结构动态规划题解:Kadane算法求最大子数组和——O(n)时间O(1)空间
c语言·数据结构·动态规划·贪心·时间复杂度·算法题·最大子数组和
鹿角片ljp21 小时前
从 Kimi Cyber Reasoning 学习网络安全推理数据集:从 Reasoning SFT 到安全 Agent 数据设计
数据结构·算法
Logic1011 天前
C语言/数据结构位运算题解:异或XOR找出数据表中的“独特编号“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
wabs6661 天前
关于二叉树【力扣100.相同的树的思考】
数据结构·c++·算法·leetcode·二叉树·递归法