Keito

© 2024 Keito

技術ブログとポートフォリオ

選択ソートアルゴリズム

最小値を選択して順番に並べるシンプルなソートアルゴリズムを学ぼう

O(n²)
時間計算量
O(1)
空間計算量
初級
難易度
ソート
カテゴリ

🔧 実行設定

配列:
[64, 25, 12, 22, 11]
要素数:
5
🎯

アルゴリズムを実行してください

左側の設定パネルから条件を設定し、「選択ソート実行」ボタンを押してください

💻 実装例(JavaScript)

function selectionSort(arr) {
    const n = arr.length;
    const sortedArray = [...arr]; // 元の配列を変更しない
    
    for (let i = 0; i < n - 1; i++) {
        // 未ソート部分から最小値のインデックスを探す
        let minIndex = i;
        
        for (let j = i + 1; j < n; j++) {
            if (sortedArray[j] < sortedArray[minIndex]) {
                minIndex = j;
            }
        }
        
        // 最小値を現在位置と交換
        if (minIndex !== i) {
            [sortedArray[i], sortedArray[minIndex]] = 
                [sortedArray[minIndex], sortedArray[i]];
        }
    }
    
    return sortedArray;
}

// 使用例
const unsortedArray = [64, 25, 12, 22, 11];
const sortedArray = selectionSort(unsortedArray);
console.log(sortedArray); // [11, 12, 22, 25, 64]