9Google AdSense

Heapsort

#include<stdio.h>
#include<conio.h>
#include<MATH.H>

void max_heapify(int A[],int i);
void build_max_heap(int A[]);
void heapsort(int A[]);
int left(int i);
int right(int i);

int length,A[30],heap_size;

int main()
{
    int p,lp;
    clrscr();
    printf("N : ");
    scanf("%d",&length);
    printf("\nEnter the number  : ");
    for(p=1;p<=length;p++)
        scanf("%d",&A[p]);
    heapsort(A);
    printf("\nThe Sorted number : ");
    for(lp=1;lp<=length;lp++)
        printf("%d ",A[lp]);
    getch();
    return 0;
}

int left(int i)
{
    return (2*i);
}
int right(int i)
{
    return ((2*i)+1);
}
void max_heapify(int A[],int i)
{
    int largest,l,r,temp;
    l=left(i);
    r=right(i);
    if((l<=heap_size)&&(A[l]>A[i]))
        largest=l;
    else
        largest=i;
    if((r<=heap_size)&&(A[r]>A[largest]))
        largest=r;
    if(largest!=i)
    {
        temp=A[i];
        A[i]=A[largest];
        A[largest]=temp;
        max_heapify(A,largest);
    }
}

void build_max_heap(int A[])
{
    int i;
    heap_size=length;
    for(i=(length/2);i>=1;i--) // be careful about this loop.
        max_heapify(A,i);
}
void heapsort(int A[])
{
    int i,temp1;
    build_max_heap(A);

    for(i=length;i>=2;i--)   // be careful about this loop.
    {
        temp1=A[1];
        A[1]=A[i];
        A[i]=temp1;
        heap_size=heap_size-1;
        max_heapify(A,1);
    }

}













No comments: