Skip to content

Instantly share code, notes, and snippets.

@todorok1
Created August 23, 2019 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todorok1/4751e6fd76edce8642cb829daf4c6fc9 to your computer and use it in GitHub Desktop.
Save todorok1/4751e6fd76edce8642cb829daf4c6fc9 to your computer and use it in GitHub Desktop.
バブルソートアルゴリズムのC#による実装例。
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