Thursday, 10 November 2016

Heap Sort Program in C++

In computer science, 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 largest element and moving that to the sorted region.
Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime.

An Example on Heap Sort: https://commons.wikimedia.org/wiki/File%3AHeapsort-example.gif 

// C++ program for implementation of Heap Sort

#include <iostream>
using namespace std;

void heapSort(int[], int);
void heapify(int[], int, int);
void display(int[], int);

//main
int main()
{
   
    int arr[] = {12, 11, 13, 5, 6, 7};
    int n = 6;  //n=size of array

    heapSort(arr, n);   //sorting array in ascending order using "Heap Sort"

    cout<<"Sorted array using Heap sort is: \n";
    display(arr, n);
    return 0;
   
}

//funtion to implement heap sort on array 'arr' of size 'n'
void heapSort(int arr[], int n)
{
    //rearrange array to build heap or heapify(max or min) the binary tree
    //(n/2-1) represents the parent of last node in a binary tree

    for (int i = n / 2 - 1; i >= 0; i--)
    {
        heapify(arr, n, i);
    }

    //Extracting the root node from the Binary tree
    for (int i=n-1; i>=0; i--)
    {
        // swapping current root to end
        int temp=arr[0];
        arr[0]=arr[i];
        arr[i]=temp;

        // call max heapify on the reduced heap
        heapify(arr, i, 0);
    }
}

/* To heapify the subtree rooted with node i which is
an index in arr[]. n=size of heap */
void heapify(int arr[], int n, int i)
{
    int largest = i;       // Initialize largest as root
    int l = 2*i + 1;       // left = 2*i + 1
    int r = l+1;           // right = 2*i + 2

    // If left child is larger than root
    //l<n indicates that l(left sub child) mustn't exceed the actual size(n) of the array 'arr'

    if (l < n && arr[l] > arr[largest])
    {
        largest = l;
    }

    // If right child is larger than largest so far
    //r<n indicates that r(right sub child) mustn't exceed the actual size(n) of the array 'arr'

    if (r < n && arr[r] > arr[largest])
    {
        largest = r;
    }

    // If largest is not root
    if (largest != i)
    {
        int temp=arr[i];
        arr[i]=arr[largest];
        arr[largest]=temp;

        // Recursively heapify the affected sub-tree
        heapify(arr, n, largest);
    }
}

//function to print sorted array of size n
void display(int arr[], int n)
{
    for (int i=0; i<n; i++)
    {
        cout<<arr[i]<<" ";
    }
}


output:
 
picture



For video reference visit: https://www.youtube.com/watch?v=51JGP4VVlDc


What am I missing here? Let me know in the comments and I'll add it in! 

No comments:

Post a Comment