Sunday, February 6, 2011

Heap Sort


OBJECTIVE: Implementation of heap sort.
THEORY: Heapsort primarily competes with quicksort, another very efficient general purpose nearly-in-place comparison-based sort algorithm. Quicksort is typically somewhat faster, due to better cache behavior and other factors, but the worst-case running time for quicksort is O(n2), which is unacceptable for large data sets and can be deliberately triggered given enough knowledge of the implementation, creating a security risk. See quicksort for a deta
PROGRAM:
#include<stdio.h>
#include<conio.h>
void restoreHup(int*,int);
void restoreHdown(int*,int,int);
void main()
{
        int a[20],n,i,j,k;
        printf("Enter the number of elements to sort : ");
        scanf("%d",&n);
        printf("Enter the elements : ");
        for(i=1;i<=n;i++){
                scanf("%d",&a[i]);
                restoreHup(a,i);
        }
        j=n;
        for(i=1;i<=j;i++)
        {
                int temp;
                temp=a[1];
                a[1]=a[n];
                a[n]=temp;
                n--;
                restoreHdown(a,1,n);
        }
        n=j;
        printf("Here is it...");
        for(i=1;i<=n;i++)
                printf("%4d",a[i]);
getct();
}
void restoreHup(int *a,int i)
{
        int v=a[i];
        while((i>1)&&(a[i/2]<v))
        {
                a[i]=a[i/2];
                i=i/2;
        }
        a[i]=v;
}
void restoreHdown(int *a,int i,int n)
{
        int v=a[i];
        int j=i*2;
        while(j<=n)
        {
                if((j<n)&&(a[j]<a[j+1]))
                        j++;
                if(a[j]<a[j/2]) break;

                a[j/2]=a[j];
                j=j*2;
        }
        a[j/2]=v;
}
OUTPUT:
Enter the number of elements to sort : 6
Enter the elements : 4 2 8 5 1 6
Here is it...   1   2   4   5   6   8

No comments:

Post a Comment