Keito

© 2024 Keito

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

配列(基本操作)

インデックスベースのランダムアクセスが可能な配列データ構造の基本操作を学ぼう

O(1)
アクセス・更新
O(n)
挿入・削除・検索
初級
難易度
ランダム
アクセス方式

🔧 操作設定

現在の配列:
[1, 2, 3, 4, 5]
選択した操作:
access(2)
配列サイズ:
5 要素
🎯 インデックス: 任意の位置に即座にアクセス可能

📚 推奨操作例

🎯

配列操作を実行してください

左側の設定パネルから操作を選択し、「配列操作実行」ボタンを押してください

💻 実装例(JavaScript)

class Array {
    constructor(size = 0) {
        this.items = new Array(size);
        this.length = 0;
    }
    
    // 指定インデックスの要素にアクセス - O(1)
    access(index) {
        if (index < 0 || index >= this.length) {
            throw new Error("インデックスが範囲外です");
        }
        return this.items[index];
    }
    
    // 指定位置に要素を挿入 - O(n)
    insert(index, value) {
        if (index < 0 || index > this.length) {
            throw new Error("挿入位置が無効です");
        }
        
        // 要素を右にシフト
        for (let i = this.length; i > index; i--) {
            this.items[i] = this.items[i - 1];
        }
        
        this.items[index] = value;
        this.length++;
        return this.length;
    }
    
    // 指定インデックスの要素を削除 - O(n)
    delete(index) {
        if (index < 0 || index >= this.length) {
            throw new Error("削除インデックスが範囲外です");
        }
        
        const deletedValue = this.items[index];
        
        // 要素を左にシフト
        for (let i = index; i < this.length - 1; i++) {
            this.items[i] = this.items[i + 1];
        }
        
        this.length--;
        return deletedValue;
    }
    
    // 指定インデックスの要素を更新 - O(1)
    update(index, value) {
        if (index < 0 || index >= this.length) {
            throw new Error("更新インデックスが範囲外です");
        }
        
        const oldValue = this.items[index];
        this.items[index] = value;
        return oldValue;
    }
    
    // 指定値を線形検索 - O(n)
    search(value) {
        for (let i = 0; i < this.length; i++) {
            if (this.items[i] === value) {
                return i; // インデックスを返す
            }
        }
        return -1; // 見つからない場合
    }
    
    // 配列の要素数を取得 - O(1)
    size() {
        return this.length;
    }
    
    // 配列の内容を表示
    display() {
        return this.items.slice(0, this.length);
    }
}

// 使用例
const array = new Array(10);

// 要素の挿入
array.insert(0, 10);
array.insert(1, 20);
array.insert(2, 30);
console.log(array.display()); // [10, 20, 30]

// 要素へのアクセス
console.log(array.access(1)); // 20

// 要素の更新
array.update(1, 25);
console.log(array.display()); // [10, 25, 30]

// 要素の検索
console.log(array.search(25)); // 1

// 要素の削除
array.delete(0);
console.log(array.display()); // [25, 30]

🎯 配列の特徴

メリット

  • • ランダムアクセスでO(1)の高速読み書き
  • • メモリ効率が良い(連続配置)
  • • キャッシュ効率が高い
  • • 実装が簡単で理解しやすい

実世界での応用

  • • データベースのレコード管理
  • • 画像処理(ピクセル配列)
  • • 数値計算(行列・ベクトル)
  • • ゲーム開発(座標・状態管理)

💡 ポイント: 配列は最も基本的なデータ構造で、 他の多くのデータ構造の基礎となっています。