Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@todorok1
Last active August 27, 2019 06:19
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/70fb77077412513fc8da96bdb816094a to your computer and use it in GitHub Desktop.
Save todorok1/70fb77077412513fc8da96bdb816094a to your computer and use it in GitHub Desktop.
コムソートアルゴリズムのC#による実装例。
using UnityEngine;
/// <Summary>
/// コムソート(コームソート)を行うスクリプトです。
/// </Summary>
public class CombSort : 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;
// 交換が発生したかどうかのフラグです。
bool isChanged = false;
// 櫛の間隔を定義します。
int h = targetArray.Length;
// 外側のループが何回実行されたかを保持する変数です。
int loopNum = 0;
// 交換回数を保持する変数です。
int swapNum = 0;
// コムソートで配列の中身を昇順で並べ替えます。
while (isChanged || h > 1){
// 櫛の間隔を計算します。
if (h > 1){
h = Mathf.FloorToInt(h / 1.3f);
}
// 処理回数を表示します。
Debug.Log($"{loopNum + 1}週目の処理 h : {h}");
isChanged = false;
for (int i = 0; i < targetArray.Length - h; i++){
// 処理回数の値を増やします。
iterationNum++;
// 指定した間隔の要素と比較し、順序が逆であれば入れ替えます。
if (targetArray[i] > targetArray[i + h]){
// 配列の要素の交換を行います。
int temp = targetArray[i];
targetArray[i] = targetArray[i + h];
targetArray[i + h] = temp;
// 交換フラグをtrueにします。
isChanged = true;
// 交換回数の値を増やします。
swapNum++;
}
}
// コンソールに配列の中身を表示します。
InspectArrayContents(targetArray);
// ループ回数のカウントを増やします。
loopNum++;
}
// コンソールに配列の中身を表示します。
Debug.Log("*** 最終結果 ***");
InspectArrayContents(targetArray);
Debug.Log($"処理回数は {iterationNum} 回、 交換回数は {swapNum} 回でした。");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment