C++ Heap Sort Most Simple Program - COFPROG

C++ Heap Sort Most Simple Program

Easiest Heap Sort CPP


This C++ program, implements the heap sort model of sorting elements. Here is the source code of the C++ program which takes the values of array as input and returns the sorted array as output. This C++ program is successfully compiled and run on CodeBlocks, a C++ compiler. The program output is also shown below.



Program:

#include<iostream>

using namespace std;

const int SIZE=10;
int n = SIZE;

void exchange(int arr[], int beg, int n)
{
int t;

t = arr[beg];
arr[beg] = arr[n];
arr[n] = t;
}

void downheap(int arr[], int i)
{
int l = 2*i + 1;
int r;
while(l<n)
{
r=l+1;
if (r<n)
{
if(arr[r]>arr[l])
{
l=r;
}
}

if(arr[i] > arr[l])
return;

exchange(arr, i, l);

i=l;
l=2*i +1;
}
}

void build_max_heap(int arr[])
{
for(int i=SIZE/2-1; i>=0; i--)
downheap(arr, i);
}

void heap_sort(int arr[])
{
build_max_heap(arr);

while(n>1)
{
n--;
exchange(arr, 0, n);
downheap(arr, 0);
}
}


int main()
{
int arr[SIZE];

cout<<"Enter 10 elements\n";
for(int i=0; i<SIZE; i++)
{
cin>>arr[i];
}

heap_sort(arr);

cout<<"After sorting:\n";
for(int i=0; i<SIZE; i++)
{
cout<<arr[i]<<endl;
}

return 0;
}

OUTPUT:

Enter 10 elements
63
51
499
01
45
1
63
97
2
4
After sorting
1
1
2
4
45
51
63
63
97
499




#COFPROG
Previous
Next Post »

1 comments:

Write comments
Mike Bronhild
AUTHOR
4 November 2019 at 10:49 delete

Unfortunately for me but these things are not very understandable. That is why I prefer using ready-made solutions, and preferably those that work in the cloud. There just sometimes just click here and many things are calculated by the application itself.

Reply
avatar