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]
相关推荐
小徐不徐说2 小时前
序列化与反序列化:把 C++ 对象可靠地保存下来
开发语言·数据库·c++·php
ragnwang2 小时前
Notes: Python pybind11 import C++ module
开发语言·c++·python
Wang's Blog2 小时前
Java 项目实战: 交友项目 - 搜索附近的功能概述和分析
java·开发语言·交友
骑着蜗牛撵大象3273 小时前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
Dxy12393102164 小时前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷4 小时前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
云和数据.ChenGuang4 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
nice_lcj5205 小时前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
椒哥6 小时前
一天被问几十次"允许",我统计了 517 次,然后写了个插件
前端·javascript·github
樱花树下的数学喵6 小时前
手写简易 STL string|C++ 字符串底层实现
开发语言·c++