C++ Code/Program For Heap Sorting Algorithm (Applied in an array of random numbers)

Leave a Comment
    /*The Following C++ Code Is For Heap Sort Algorithm Implementation. In this program the array element get assign with a random value, in the range of 0 to 100 by using rand() function & then the heap sorting algorithm is applied */
    
#include <iostream>
#include <stdlib.h>
    
    using namespace std;
     

    
   void percolateDown(int array[], int size, int id) 
    {                  //function to perform prelocate the element down
            int current = id;
            int max;
            while(true) {
                    int left = current*2+1;
                    int right = current*2+2;
                    if(left >= size)
                            return;
                    else if(right >= size)
                            max = left;
                    else if(array[left] > array[right])
                            max = left;
                    else if(array[left] < array[right])
                            max = right;
                    if(array[max] > array[current]) {
                            int temp = array[max];
                            array[max] = array[current];
                            array[current] = temp;
                            current = max;
                    } else
                            return;
            }
    }


     void buildheap(int array[], int size) {  //function to build a heap
            for(int i=size/2; i>=0; i--) {
                    percolateDown(array, size, i);
            }
    }


     void heapsort(int array[], int size) {  //Function to perform heap sorting
            buildheap(array, size);
            int heapsize = size;
    
            for(int i=size-1; i>0; i--) {
                    int temp = array[i];
                    array[i] = array[0];
                    array[0] = temp;
                    heapsize--;
                    percolateDown(array, heapsize, 0);
            }
    }
     

    void printArray(int array[], int size) { //Program to print array
            for(int i=0; i<size; i++) {
                    cout << array[i] << " ";
            }
            cout << endl;
    }
    
    int main() {
            const int size = 20;
            int arrayToSort[size];
            for(int i=0; i<size; i++)
            arrayToSort[i] = 1+rand()%100;
//assign every element of arrat a number between 1 & 100
    //instead of assigning random numbers you can also ask the user to enter numbers at the above step
            printArray(arrayToSort, size);
    
            heapsort(arrayToSort, size);
    
            printArray(arrayToSort, size);
            system("pause");
    }
    

Screenshots:
Heap Sort Algorithm Output When Applied For An Array Of Random Numbers, C++ COde for Heap Sorting Algorithm
Heap Sort Algorithm Output When Applied For An Array Of Random Numbers
 

0 comments: