バブルソートアルゴリズムの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 BubbleSort : 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 = 0; i < targetArray.Length; i++){ | |
Debug.Log($"{i + 1}週目の処理"); | |
// 要素の比較を行います。最後の要素は外側のループが終了するごとに確定します。 | |
for (int j = 1; j < targetArray.Length - i; j++){ | |
// 処理回数の値を増やします。 | |
iterationNum++; | |
// 隣り合う要素と比較し、順序が逆であれば入れ替えます。 | |
if (targetArray[j] < targetArray[j - 1]){ | |
// 配列の要素の交換を行います。 | |
int temp = targetArray[j]; | |
targetArray[j] = targetArray[j - 1]; | |
targetArray[j - 1] = temp; | |
} | |
} | |
// コンソールに配列の中身を表示します。 | |
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