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.
Here is source code of the C++ Program to Sort an Array of 10 Elements Using Heap Sort Algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Implement Heap Sort
*/
#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;
}
Output:
$ g++ HeapSort.cpp $ a.out Enter no of elements to be sorted: 20 Elements are: 46 81 76 98 55 30 58 57 71 57 21 65 51 68 70 63 93 53 78 53 Sorted elements are: 21 30 46 51 53 53 55 57 57 58 63 65 68 70 71 76 78 81 93 98 Enter no of elements to be sorted: 10 Elements are: 6 64 84 52 49 32 28 93 39 13 Sorted elements are: 6 13 28 32 39 49 52 64 84 93 ------------------ (program exited with code: 0) Press return to continue
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Programming Books
- Apply for Information Technology Internship
- Apply for Computer Science Internship
- Buy C++ Books
- Buy Computer Science Books