0% found this document useful (0 votes)
13 views2 pages

Using System 2

The document contains a C# implementation of the Max Heap Sort algorithm. It includes methods for sorting an array, heapifying elements, and printing the sorted array. The main driver program demonstrates the sorting of a predefined integer array.

Uploaded by

rakanghassan60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Using System 2

The document contains a C# implementation of the Max Heap Sort algorithm. It includes methods for sorting an array, heapifying elements, and printing the sorted array. The main driver program demonstrates the sorting of a predefined integer array.

Uploaded by

rakanghassan60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

;using System

class MaxHeapSort
}
public static void Sort(int[] arr)
}
;int n = arr.Length

for (int i = n / 2 - 1; i >= 0; i--)


;Heapify(arr, n, i)

for (int i = n - 1; i > 0; i--)


}

;int temp = arr[0]


;arr[0] = arr[i]
;arr[i] = temp

;Heapify(arr, i, 0)
{
{

static void Heapify(int[] arr, int n, int i)


}
;int largest = i
;int left = 2 * i + 1
;int right = 2 * i + 2

If left child is larger than root //


if (left < n && arr[left] > arr[largest])
;largest = left

If right child is larger than largest so far //


if (right < n && arr[right] > arr[largest])
;largest = right
If largest is not root //
if (largest != i)
}
;int swap = arr[i]
;arr[i] = arr[largest]
;arr[largest] = swap

;Heapify(arr, n, largest)
{
{

A utility function to print array of size n //


static void PrintArray(int[] arr)
}
;int n = arr.Length
for (int i = 0; i < n; ++i)
;Console.Write(arr[i] + " ")
;()Console.WriteLine
{

Driver program //
()public static void Main
}
;int[] arr = { 2, 22, 9, 19, 27, 18, 15, 5, 14, 21, 3, 4, 11 }

;Console.WriteLine("Original array:")
;PrintArray(arr)

;Sort(arr)

;Console.WriteLine("\nMax Heap Sorted array:")


;PrintArray(arr)
{
{

You might also like