ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

C# program to implement the Heap Sort

Here, we are going to learn how to implement the Heap Sort in C#?
Submitted by Nidhi, on November 07, 2020

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

Program:

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.

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.