js选择排序

javascript 复制代码
    function selectionSort(arr) {
        const len = arr.length
 
        // 每一次外循环确定一个最小值(因为是作比较,次数是数组长度-1)
        for(let i = 0; i < len - 1; i++) {
            // 假设当前索引为 i 的元素是最小的
            let minIndex = i
 
            // 每一次内循环两两比较(因为要比完数组剩下所有数,所以 j < 数组长度len)
            for(let j = i + 1; j < len; j++) {
                if(arr[j] < arr[minIndex]) {
                    minIndex = j
                }
            }
 
            // 将最小元素与当前索引的元素进行交换
            [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]
        }
        return arr
    }
    
    const nums = [4, 5, 2, 7, 8]
    console.log(selectionSort(nums))  // [2, 4, 5, 7, 8]
相关推荐
GISer_Jing1 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩1 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
AI玫瑰助手1 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车1 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋1 小时前
C++14特性
开发语言·c++·c++14特性
JAVA社区3 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子3 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php
z落落3 小时前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#
学代码的真由酱3 小时前
Java多用户一对一网页聊天室-测试报告
java·开发语言·功能测试·测试
人道领域3 小时前
【LeetCode刷题日记】669.修剪二叉搜索树
开发语言·python·算法