SoFunction
Updated on 2025-03-07

C# sorting algorithm heap sorting

This article has shared the specific code for C# to implement heap sorting for your reference. The specific content is as follows

Code:

/// <summary> 
  /// Heap sorting method.  /// </summary> 
  /// <param name="a"> 
  /// Array to be sorted.  /// </param> 
  private void Heapsort(int[] a)
  {
   HeapSort_BuildMaxHeap(a); // Create a large root pile.   ("Build max heap:");
   foreach (int i in a)
   {
    (i + " "); // Print a large root pile.   }
 
   ("\r\nMax heap in each iteration:");
   for (int i =  - 1; i > 0; i--)
   {
    HeapSort_Swap(ref a[0], ref a[i]); // Exchange the heap top element with the last element of the unordered area.    HeapSort_MaxHeaping(a, 0, i); // Adjust the new disordered area to a large root heap. 
    // Print the large root heap after each heap sort iteration.    for (int j = 0; j < i; j++)
    {
     (a[j] + " ");
    }
 
    ();
   }
  }
 
  /// <summary> 
  /// Build stack from bottom to top.  From the properties of the completely binary tree, we can see that the leaf node starts from index=/2, so the large root heap is adjusted from the bottom to the upward from the index=(/2)-1 node.  /// </summary> 
  /// <param name="a"> 
  /// Array to be sorted.  /// </param> 
  private static void HeapSort_BuildMaxHeap(int[] a)
  {
   for (int i = ( / 2) - 1; i >= 0; i--)
   {
    HeapSort_MaxHeaping(a, i, );
   }
  }
 
  /// <summary> 
  /// Adjust the specified node to a heap.  /// </summary> 
  /// <param name="a"> 
  /// Array to be sorted.  /// </param> 
  /// <param name="i"> 
  /// The node that needs to be adjusted.  /// </param> 
  /// <param name="heapSize"> 
  /// The size of the heap also indicates the length of the unordered area in the array.  /// </param> 
  private static void HeapSort_MaxHeaping(int[] a, int i, int heapSize)
  {
   int left = (2 * i) + 1; // Left sub-node.   int right = 2 * (i + 1); // Right sub-node.   int large = i; // Temporary variable, storing the large node value. 
   // Compare the left sub-node.   if (left < heapSize && a[left] > a[large])
   {
    large = left;
   }
 
   // Compare the right subnode.   if (right < heapSize && a[right] > a[large])
   {
    large = right;
   }
 
   // If the sub-nodes are larger than themselves, exchange them to move the large element upwards; and adjust the large element to the heap to ensure the properties of the heap.   if (i != large)
   {
    HeapSort_Swap(ref a[i], ref a[large]);
    HeapSort_MaxHeaping(a, large, heapSize);
   }
  }
 
  /// <summary> 
  /// Swap the values ​​of two integers.  /// </summary> 
  /// <param name="a">Integer a.  </param>  /// <param name="b">Integer b.  </param>  private static void HeapSort_Swap(ref int a, ref int b)
  {
   int tmp = a;
   a = b;
   b = tmp;
  }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.