0% found this document useful (0 votes)
30 views4 pages

Experiment-6: Program To Implement Heap Sort Algorithm

This document contains code to implement a heap sort algorithm in C++. It includes functions to perform max heapify on an array, build a max heap from an array, perform the heap sort, and test the algorithm on user-input data. The heapify function moves elements in the array to satisfy the max heap property. The heap sort function repeatedly extracts the maximum element to the end of the array and max heapifies the remaining elements.

Uploaded by

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

Experiment-6: Program To Implement Heap Sort Algorithm

This document contains code to implement a heap sort algorithm in C++. It includes functions to perform max heapify on an array, build a max heap from an array, perform the heap sort, and test the algorithm on user-input data. The heapify function moves elements in the array to satisfy the max heap property. The heap sort function repeatedly extracts the maximum element to the end of the array and max heapifies the remaining elements.

Uploaded by

Shruti Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 4

EXPERIMENT-6

Program to implement heap sort algorithm.

#include<iostream.h>

#include<conio.h>

// A function to heapify the array.

void MaxHeapify(int a[], int i, int n)

int j, temp;

temp = a[i];

j = 2*i;

while (j <= n)

if (j < n && a[j+1] > a[j])

j = j+1;

// Break if parent value is already greater than child value.

if (temp > a[j])

break;

// Switching value with the parent node if temp < a[j].

else if (temp <= a[j])

a[j/2] = a[j];

j = 2*j;
}

a[j/2] = temp;

return;

void HeapSort(int a[], int n)

int i, temp;

for (i = n; i >= 2; i--)

// Storing maximum value at the end.

temp = a[i];

a[i] = a[1];

a[1] = temp;

// Building max heap of remaining element.

MaxHeapify(a, 1, i - 1);

void Build_MaxHeap(int a[], int n)

int i;

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

MaxHeapify(a, i, n);

}
int main()

int n, i;

cout<<"\nEnter the number of data element to be sorted: ";

cin>>n;

n++;

int arr[n];

for(i = 1; i < n; i++)

cout<<"Enter element "<<i<<": ";

cin>>arr[i];

// Building max heap.

Build_MaxHeap(arr, n-1);

HeapSort(arr, n-1);

// Printing the sorted data.

cout<<"\nSorted Data ";

for (i = 1; i < n; i++)

cout<<"->"<<arr[i];

return 0;

getch();
}

You might also like