C# - Heap Sort Program

Here, we are going to learn how to implement the Heap Sort in C#? By Nidhi Last updated : March 28, 2023

Here, we will sort an integer array using Heap Sort.

C# program to implement the Heap Sort

The source code to sort an integer array using heap sort is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// C# program to implement the Heap Sort

using System;

class Sort {
  private void Adjust(int[] arr, int i, int n) {
    int temp = 0;
    int loop = 0;

    temp = arr[i];
    loop = 2 * i;
    while (loop <= n) {
      if (loop < n && arr[loop] < arr[loop + 1])
        loop++;
      if (temp >= arr[loop])
        break;
      arr[loop / 2] = arr[loop];
      loop = loop * 2;
    }
    arr[loop / 2] = temp;
  }

  public void HeapSort(int[] arr) {
    int loop = 0;
    int temp = 0;
    for (loop = 5; loop >= 0; loop--) {
      Adjust(arr, loop, 9);
    }
    for (loop = 8; loop >= 0; loop--) {
      temp = arr[loop + 1];
      arr[loop + 1] = arr[0];
      arr[0] = temp;
      Adjust(arr, 0, loop);
    }
  }

  public static void Main() {
    int loop = 0;
    int[] arr = {22, 51, 21, 10, 36, 59, 33, 67, 64, 18};

    Sort H = new Sort();

    H.HeapSort(arr);

    Console.WriteLine("Sorted Array: ");
    for (loop = 0; loop < arr.Length; loop++)
      Console.Write(arr[loop] + " ");

    Console.WriteLine();
  }
}

Output

Sorted Array:
10 18 21 22 33 36 51 59 64 67
Press any key to continue . . .

Explanation

In the above program, we created a class Sort that contains three static methods HeapSort(), Adjust(), and Main().

The HeapSort() method is used to implement heap sort algorithm to sort the integer array in the ascending order, and the Main() method is the entry point for the program. Here we created an integer array and then called HeapSort() method that will sort the array in the ascending order and printed the sorted array on the console screen.

C# Data Structure Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.