Saturday 3 October 2015

Heap sort

Today we will be discussing about Heap sort. This sorting first tries to build a max heap and once you get a max heap . you can easily sort the element by swapping the maximum element with last element. you can read the theory from standard book "clrs" or  Wikipedia if you don't know what is max heap

Here is the program for heap sort. i am using three functions first one is heapsort which will sort the elements once you get max heap in order to build max heap i am calling a function called building_max_heap which will max_heapify function to build a max heap for random numbers 

#include<stdio.h>
int heap_size;
void main()
{
    int A[]={23,65,2,6,12,43,76,845,93,86};
    heap_size=sizeof A/sizeof A[0];
    heap_sort(A);
}

void heap_sort(int *A)
{
    int n ;
    building_max_heap(A);
    for(n=heap_size-1;n>=0;n--)
    {
        printf("%d\n",A[0]);
        swap(&A[n],&A[0]);
        heap_size= heap_size-1;
        max_heapify(A,0);
    }

}

void building_max_heap(int *A)       /* this function will create a max heap on random array by using                                                                max_heapify function */
{
    int i,n = heap_size-1;        /*heap size is the last index +1 as index is starting from 0 */
    for(i=(n-1)/2;i>=0;i--)       /*as internal nodes will start from (n-1)/2 in almost complete binary tree                                                   and the leaves are already in heap */
    {
        max_heapify(A,i);
    }

}


void max_heapify(int *A,int i)   /*this function will assume that left and right children of i are already                                                       in heap now we want to add the ith element( i.e. root) in heap */  
{
    int left = 2*i+1;
    int right= 2*i+2;
    int max;
    if(A[left]>A[i]&&left<=heap_size-1)
    {
        max = left;
    }
    else max= i ;
    if(A[right]>A[max]&&right<=heap_size-1)
    {
        max= right;
    }
    if (max!=i)
    {
        swap(&A[i],&A[max]);
        max_heapify(A,max);
    }

}


void swap(int *m, int *n)
{
    int temp = *m;
    *m=*n;
    *n=temp;
}

No comments:

Post a Comment