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]
相关推荐
阿里加多19 分钟前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
likerhood36 分钟前
java中`==`和`.equals()`区别
java·开发语言·python
小李子呢02111 小时前
前端八股性能优化(2)---回流(重排)和重绘
前端·javascript
zs宝来了1 小时前
AQS详解
java·开发语言·jvm
程序员buddha2 小时前
深入理解ES6 Promise
前端·ecmascript·es6
吴声子夜歌2 小时前
ES6——Module详解
前端·ecmascript·es6
telllong2 小时前
Python异步编程从入门到不懵:asyncio实战踩坑7连发
开发语言·python
吴声子夜歌3 小时前
Vue3——Vue实例与数据绑定
前端·javascript·vue.js
wjs20244 小时前
JavaScript 条件语句
开发语言
阿里加多4 小时前
第 1 章:Go 并发编程概述
java·开发语言·数据库·spring·golang