# 经典排序算法-02-选择排序

function selectionSort(arr) {
    if(!arr.length) return []
    if(arr.length === 1) return arr
    
    let sorted = 0
    while(sorted < arr.length) {
        let indexOfMin = sorted
        let temp = arr[sorted]
        for (let i = sorted+1; i < arr.length; i++) {
            if(temp > arr[i]) {
                temp = arr[i]
                indexOfMin = i
            }
        }
        // 位置对调
        // arr[sorted] = arr[indexOfMin]
        // arr[indexOfMin] = temp
        [arr[sorted],arr[indexOfMin]] = [arr[indexOfMin],arr[sorted]]
        sorted += 1
    }

    return arr
}

const nums = [3,5,9,7,4,2,10]
const ret = selectionSort(nums)
console.log('[Final Result]:', ret)
Last Updated: 2019-12-2 17:46:54

~扫码关注<码路工人>了吗?~

~关注公众号可以第一时间获取最新文章~

~扫码关注可以联系交流~

WeChatQRCode