Created
August 29, 2019 12:10
-
-
Save todorok1/f142e9d055ace5485729a3c79cacf74a to your computer and use it in GitHub Desktop.
挿入ソートアルゴリズムのC#による実装例。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
/// <Summary> | |
/// 挿入ソートを行うスクリプトです。 | |
/// </Summary> | |
public class InsertionSort : SortBase { | |
void Start(){ | |
ExecuteSort(); | |
} | |
void ExecuteSort(){ | |
// ソートしたい配列を定義します。 | |
int[] targetArray = new int[11]{26, 400, 19, 504, 8, 500, 58, 14, 401, 168, 13}; | |
// コンソールに配列の中身を表示します。 | |
InspectArrayContents(targetArray); | |
// 処理回数を保持する変数です。 | |
int iterationNum = 0; | |
// 挿入ソートで配列の中身を並べ替えます。 | |
for (int i = 1; i < targetArray.Length; i++){ | |
// 比較を行う値を保持する変数です。 | |
int key = targetArray[i]; | |
Debug.Log($"key : {key}"); | |
// 移動先のインデックスを保持する変数です。 | |
int destIndex = i; | |
// 要素の比較を行います。 | |
for (int j = i - 1; j >= 0; j--){ | |
// 処理回数の値を増やします。 | |
iterationNum++; | |
// キーと比較し、キーより大きな値であれば次の要素に値をずらします。 | |
if (targetArray[j] > key){ | |
targetArray[j + 1] = targetArray[j]; | |
// 条件を満たしている時のインデックスを移動先として保存します。 | |
destIndex = j; | |
} | |
} | |
// 保存した値を確認中の要素に挿入します。 | |
targetArray[destIndex] = key; | |
// コンソールに配列の中身を表示します。 | |
InspectArrayContents(targetArray); | |
} | |
// コンソールに配列の中身を表示します。 | |
Debug.Log("*** 最終結果 ***"); | |
InspectArrayContents(targetArray); | |
Debug.Log($"処理回数は {iterationNum} 回でした。"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment