
以下はC#でのセレクションソートのコード例です。
public class SelectionSort
{
public static void Main(string[] args)
{
int[] array = { 64, 25, 12, 22, 11 };
Console.WriteLine("Array before sorting:");
PrintArray(array);
SelectionSortAlgorithm(array);
Console.WriteLine("Array after sorting:");
PrintArray(array);
}
public static void SelectionSortAlgorithm(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void PrintArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
}
このコードでは、整数型の配列をセレクションソートでソートする例を示しています。メインメソッドで配列を定義し、ソート前後の状態を表示します。選択ソートアルゴリズムはSelectionSortAlgorithm
メソッド内に実装されており、配列内の最小要素を見つけて現在の位置と交換する操作を繰り返します。PrintArray
メソッドは配列を表示するために使用されます。
上記のコードを実行すると、セレクションソートによって配列がソートされ、ソート前後の結果が表示されます。
その他のアルゴリズム
