C++ Programming Code Examples C++ > Computer Graphics Code Examples Program to Sort an Array of 10 Elements Using Heap Sort Algorithm Program to Sort an Array of 10 Elements Using Heap Sort Algorithm This is a C++ Program to sort given numbers using heap sort algorithm. Heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the smallest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the minimum. #include <iostream> #include <conio.h> #include <cstdlib> #include <time.h> using namespace std; const int LOW = 1; const int HIGH = 100; void max_heapify(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; if (temp > a[j]) break; 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--) { temp = a[i]; a[i] = a[1]; a[1] = temp; max_heapify(a, 1, i - 1); } } void build_maxheap(int *a, int n) { int i; for (i = n / 2; i >= 1; i--) { max_heapify(a, i, n); } } int main() { int n, i; cout << "Enter no of elements to be sorted:"; cin >> n; int a[n]; time_t seconds; time(&seconds); srand((unsigned int) seconds); cout << "Elements are:\n"; for (i = 1; i <= n; i++) { a[i] = rand() % (HIGH - LOW + 1) + LOW; cout << a[i] << " "; } build_maxheap(a, n); heapsort(a, n); cout << "\nSorted elements are:\n"; for (i = 1; i <= n; i++) { cout << a[i] << " "; } return 0; }