Exp10 Heapsort in C++
Exp10 Heapsort in C++
Title:
Read the marks obtained by students of second year in an online examination of
particular subject. Find out maximum and minimum marks obtained in a that subject. Use heap
data structure. Analyze the algorithm.
Objectives:
Learning Objectives:
To understand concept of heap
To understand concept & features like max heap, min heap.
Learning Outcome:
Theory:
Theory:
Heap is a special case of balanced binary tree data structure where the root-node key is
compared with its children and arranged accordingly. If α has child node β then −
key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap.
Based on this criteria, a heap can be of two types −
For Input → 35 33 42 10 14 19 27 44 26 31
Min-Heap − Where the value of the root node is less than or equal to either of its children.
Max-Heap − Where the value of the root node is greater than or equal to either of its children.
Both trees are constructed using the same input and order of arrival.
Note − In Min Heap construction algorithm, we expect the value of the parent node to be less
than that of the child node.
Let's understand Max Heap construction by an animated illustration. We consider the same input
sample that we used earlier.
INPUT:35,33,42,10,14,19,27,44,16,31
Conclusion: This program gives us the knowledge of heap and its types
Program:
#include <iostream>
using namespace std;
class heap1{
public:
if((r<=n)&&(a[r]>a[largest]))
largest=r;
if(largest!=i)
{
loc=a[i];
a[i]=a[largest];
a[largest]=loc;
MAX_HEAPIFY(a, largest,n);
}
}
void BUILD_MAX_HEAP(int a[], int n)
{
for(int k = n/2; k >= 1; k--)
{
MAX_HEAPIFY(a, k, n);
}
}
void HEAPSORT(int a[], int n)
{
BUILD_MAX_HEAP(a,n);
int i, temp;
for (i = n; i >= 2; i--)
{
temp = a[i];
a[i] = a[1];
a[1] = temp;
MAX_HEAPIFY(a, 1, i - 1);
}
}
void accept(){
int n;
cout<<"Enter the number of students"<<endl;
cin>>n;
int a[n];
cout<<"Enter the marks of the students "<<endl;
for (int i = 1; i <= n; i++)
{
cin>>a[i];
}
HEAPSORT(a, n);
display(a,n);
}
void display(int a[],int n){
cout<<":::::::SORTED MARKS::::::"<<endl;
}
};
int main()
{
heap1 h;
h.accept();
return 0;
}