Monday, December 2, 2019

Heap Sort in C++

I wrote this program that will accept ten numbers and then the program will sort the given number and display the sorted values using a heap sort algorithm using the C++ programming language.

I am currently accepting programming work, IT projects, school and application development, programming projects, thesis and capstone projects, IT consulting work, computer tutorials, and web development work kindly contact me in the following email address for further details.  If you want to advertise on my website kindly contact me also in my email address also. Thank you.

My email address is the following jakerpomperada@gmail.com, jakerpomperada@aol.com, and jakerpomperada@yahoo.com.

My mobile number here in the Philippines is 09173084360.

My telephone number at home here in Bacolod City, Negros Occidental Philippines is  +63 (034) 4335675.

Here in Bacolod City, Negros Occidental I also accepting computer repair, networking and Arduino Project development at a very affordable price.


My personal website is http://www.jakerpomperada.com

My programming website is http://www.jakerpomperada.blogspot.com

I am also a book author you can purchase my books on computer programming and information technology in the following links below.




Thank you very much for your help and support.




Sample Program Output


Program Listing

heap_sort.cpp

// heap_sort.cpp
// Jake R. Pomperada, MAED-IT
// December 2, 2019

#include <iostream>

using namespace std;

void heapify(int array[], int len, int i)
{
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if (left < len && array[left] > array[largest])
        largest = left;

    if (right < len && array[right] > array[largest])
        largest = right;

    if (largest != i)
    {
        swap(array[i], array[largest]);

        heapify(array, len, largest);
    }
}

void heapSort(int array[], int len)
{
    for (int i = len / 2 - 1; i >= 0; i--)
        heapify(array, len, i);

    for (int i = len - 1; i >= 0; i--)
    {
        swap(array[0], array[i]);
        heapify(array, i, 0);
    }
}

void print(int array[], int len)
{
    cout <<"\t";
    for (int i = 0; i < len; ++i)
        cout <<" " << array[i] << " ";
    cout << endl;
}

int main()
{
 int array[10];

 cout <<"\n\n";
 cout << "\tHeap Sort in C++";
 cout <<"\n\n";
 for (int a=0; a<10; a++) {
    cout << "\tEnter item value number " <<a+1 <<" : ";
cin >> a[array]; 
  }
  cout <<"\n\n";
  cout << "\tUnSorted array: \n";
  cout <<"\n ";
  cout <<"\t";
  for (int a=0; a<10; a++) {
  cout <<" " <<a[array] <<" ";
  }
  cout <<"\n\n";
  cout << "\tSorted array: \n";
  cout <<"\n";
  int len = sizeof(array) / sizeof(array[0]);
  heapSort(array, len);
  print(array, len);
  cout <<"\n";
  cout <<"\tEnd of Program";
  cout <<"\n";
}

No comments:

Post a Comment