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

implement heap data structure 10

The document contains a C++ implementation of a heap data structure with methods for max heapification, building a max heap, and performing heap sort. It includes a user interface for accepting student marks, sorting them using heap sort, and displaying the sorted marks along with the minimum and maximum values. The program uses 1-based indexing for the heap array.

Uploaded by

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

implement heap data structure 10

The document contains a C++ implementation of a heap data structure with methods for max heapification, building a max heap, and performing heap sort. It includes a user interface for accepting student marks, sorting them using heap sort, and displaying the sorted marks along with the minimum and maximum values. The program uses 1-based indexing for the heap array.

Uploaded by

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

#include <iostream>

using namespace std;

class HEAP {
public:
void MAX_HEAPIFY(int [], int, int);
void BUILD_MAX_HEAP(int [], int);
void HEAPSORT(int [], int);
void ACCEPT();
void DISPLAY(int [], int);
};

void HEAP::MAX_HEAPIFY(int a[], int i, int n) {


int l, r, largest, loc;
l = 2 * i; // Left child
r = 2 * i + 1; // Right child
if ((l <= n) && (a[l] > a[i])) {
largest = l;
} else {
largest = i;
}
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 HEAP::BUILD_MAX_HEAP(int a[], int n) {


for (int k = n / 2; k >= 1; k--) {
MAX_HEAPIFY(a, k, n);
}
}

void HEAP::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 HEAP::ACCEPT() {
int n;
cout << "\nEnter the number of students: ";
cin >> n;
int a[n + 1]; // Array to store heap (1-based indexing)
cout << "\nEnter the marks of the students:" << endl;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
HEAPSORT(a, n); // Sort using heap sort
DISPLAY(a, n); // Display sorted marks
}

void HEAP::DISPLAY(int a[], int n) {


cout << "\n:::::::SORTED MARKS::::::\n" << endl;
for (int i = 1; i <= n; i++) {
cout << a[i] << endl;
}
cout << "\nMinimum marks obtained are: " << a[1];
cout << "\nMaximum marks obtained are: " << a[n];
}

int main() {
HEAP h;
h.ACCEPT();
return 0;
}

You might also like