Skip to content

Instantly share code, notes, and snippets.

@todorok1
Created August 24, 2019 08: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/98a6560c86dd09ae1391bbf87b0f8128 to your computer and use it in GitHub Desktop.
Save todorok1/98a6560c86dd09ae1391bbf87b0f8128 to your computer and use it in GitHub Desktop.
シェーカーソートアルゴリズムのC#による実装例。
using UnityEngine;
/// <Summary>
/// バブルソートを改良したシェーカーソートを行うスクリプトです。
/// </Summary>
public class ShakerSort : 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;
// 交換対象の範囲で先頭のインデックスを格納する変数です。
int topIndex = 0;
// 交換対象の範囲で最後尾のインデックスを格納する変数です。
int bottomIndex = targetArray.Length - 1;
// 外側のループが何回実行されたかを保持する変数です。
int loopNum = 0;
// シェーカーソートで配列の中身を昇順で並べ替えます。
while (true){
// 処理回数を表示します。
Debug.Log($"{loopNum + 1}週目の処理");
// 最後に交換したインデックスを格納する変数です。
int lastSwapIndex = topIndex;
// 配列の前から後ろに向かって比較を行います。
for (int i = topIndex; i < bottomIndex; i++){
// 処理回数の値を増やします。
iterationNum++;
// 隣り合う要素と比較し、順序が逆であれば入れ替えます。
if (targetArray[i] > targetArray[i + 1]){
// 配列の要素の交換を行います。
int temp = targetArray[i + 1];
targetArray[i + 1] = targetArray[i];
targetArray[i] = temp;
// 交換を行なった要素のインデックスを保存します。
lastSwapIndex = i;
}
}
// 最後に交換を行なったインデックスを後方の開始インデックスに設定します。
bottomIndex = lastSwapIndex;
// コンソールに配列の中身を表示します。
InspectArrayContents(targetArray);
// 交換範囲の確認を行い、全ての交換が終わっていたらwhileループを抜けます。
if (topIndex == bottomIndex){
break;
}
// 配列の後ろから前に向かって比較を行います。
lastSwapIndex = bottomIndex;
for (int i = bottomIndex; i > topIndex; i--){
// 処理回数の値を増やします。
iterationNum++;
// 隣り合う要素と比較し、順序が逆であれば入れ替えます。
if (targetArray[i] < targetArray[i - 1]){
// 配列の要素の交換を行います。
int temp = targetArray[i - 1];
targetArray[i - 1] = targetArray[i];
targetArray[i] = temp;
// 交換を行なった要素のインデックスを保存します。
lastSwapIndex = i;
}
}
// 最後に交換を行なったインデックスを前方の開始インデックスに設定します。
topIndex = lastSwapIndex;
// コンソールに配列の中身を表示します。
InspectArrayContents(targetArray);
// 交換範囲の確認を行い、全ての交換が終わっていたらwhileループを抜けます。
if (topIndex == bottomIndex){
break;
}
// ループ回数のカウントを増やします。
loopNum++;
}
// コンソールに配列の中身を表示します。
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