js 選擇算法

// 選擇排序算法

// 選擇排序算法是一種原地址比較排序算法。
// 選擇排序大體的思路是找數據結構中的最小值並將其放置在第一位。找到第二小的的值放置的第二類,以此類推數據結構

// 每一次內循環遍歷尋找最小數,記錄下minIndex,並在此次內循環後交換minIndex和i的位置code

function swap(arr, indexA, indexB) {排序

return [arr[indexA], arr[indexB]] = [arr[indexB], arr[indexA]];

}io

function selectionSort(arr) {console

let len = arr.length;
for (let i = 0; i < len; i++) {
    let minIndex = i;
    for (let j = i + 1; j < len; j++) {
        if (arr[j] < arr[minIndex]) {
            minIndex = j;
        }
    }
    if (i != minIndex ) {
        swap(arr, i, minIndex);
    }
}
return arr;

}function

const arr = [91, 60, 96, 7, 35, 65, 10, 65, 9, 30, 20, 31, 77, 81, 24];
console.log(selectionSort(arr));select

相關文章
相關標籤/搜索