
以下はC#でのヒープソートのコード例です。
public class HeapSort
{
public static void Main(string[] args)
{
int[] array = { 64, 25, 12, 22, 11 };
Console.WriteLine("Array before sorting:");
PrintArray(array);
HeapSortAlgorithm(array);
Console.WriteLine("Array after sorting:");
PrintArray(array);
}
public static void HeapSortAlgorithm(int[] arr)
{
int n = arr.Length;
// Build a max heap
for (int i = n / 2 - 1; i >= 0; i--)
{
Heapify(arr, n, i);
}
// Extract elements from the heap in descending order
for (int i = n - 1; i > 0; i--)
{
// Move current root (maximum element) to the end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Max heapify the reduced heap
Heapify(arr, i, 0);
}
}
public static void Heapify(int[] arr, int n, int root)
{
int largest = root;
int leftChild = 2 * root + 1;
int rightChild = 2 * root + 2;
// If left child is larger than root
if (leftChild < n && arr[leftChild] > arr[largest])
{
largest = leftChild;
}
// If right child is larger than largest so far
if (rightChild < n && arr[rightChild] > arr[largest])
{
largest = rightChild;
}
// If largest is not the root
if (largest != root)
{
int swap = arr[root];
arr[root] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
Heapify(arr, n, largest);
}
}
public static void PrintArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
}
このコードでは、整数型の配列をヒープソートでソートする例を示しています。メインメソッドで配列を定義し、ソート前後の状態を表示します。ヒープソートアルゴリズムはHeapSortAlgorithm
メソッド内に実装されており、まず与えられた配列を最大ヒープ(max heap)として構築し、その後、ヒープから要素を取り出して降順に並べます。Heapify
メソッドは、与えられたノードを根とする部分ヒープを再帰的に整理するために使用されます。PrintArray
メソッドは配列を表示するために使用されます。
上記のコードを実行すると、ヒープソートによって配列がソートされ、ソート前後の結果が表示されます。
その他のアルゴリズム
