Heapsort algorithm is a comparison-based sorting algorithm. The heap sort works as its name suggests. It begins by building a heap out of the data set, and then removing the largest item and placing it at the end of the sorted array. After removing the largest item, it reconstructs the heap, removes the largest remaining item, and places it in the next open position from the end of the sorted array. This is repeated until there are no items left in the heap and the sorted array is full. Elementary implementations require two arrays - one to hold the heap and the other to hold the sorted elements.
Heapsort inserts the input list elements into a heap data structure. The largest value (in a max-heap) or the smallest value (in a min-heap) are extracted until none remain, the values having been extracted in sorted order. The heap's invariant is preserved after each extraction, so the only cost is that of extraction.
During extraction, the only space required is that needed to store the heap. In order to achieve constant space overhead, the heap is stored in the part of the input array that has not yet been sorted. (The structure of this heap is described at Binary heap: Heap implementation.)
Heapsort uses two heap operations: insertion and root deletion. Each extraction places an element in the last empty location of the array. The remaining prefix of the array stores the unsorted elements.
Worst case performance | O(nlogn) |
---|---|
Best case performance | O(nlogn)[1] |
Average case performance | O(nlogn) |
Worst case space complexity | O(n) total, O(1)auxiliary |
Heap Sort Program
#include <stdio.h>
#include <conio.h>
void main()
{
int i,v,p,l[100],n,k,t,j;
clrscr();
printf("enter the number");
scaf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&l[i]);
}
printf("\nentered list are as follows");
for(i=1;i<=n;i++)
{
printf("\t%d",l[i]);
}
/*creation of heap*/
for(k=2;k<=n;k++)
{
i=k;
t=l[k];
j=i/2;
while((i>1)&&(t > l[j]))
{
l[i]=l[j];
i=j;
j=i/2;
if(j<1)
j=1;
}
l[i]=t;
}
printf("\nHEAP");
for(i=1;i<=n;i++)
{
printf("\t%d",l[i]);
}
printf("\n");
//heapsort
for(k=n;k>=2;--k)
{
t=l[1];
l[1]=l[k];
l[k]=t;
i=1;
v=l[1];
j=2;
if(j+1)
if(l[j+1]>l[j])
j++;
while((j<=(k-1))&&(l[j]>v))
{
l[i]=l[j];
i=j;
j=2*i;
if(j+1)
if(l[j+1]>l[j])
j++;
else
if(j>n)
j=n;
l[i]=v;
}
for(p=1;p<=n;p++)
{
printf("\t%d",l[p]);
}
printf("\n");
}
printf("\nthe sorted list ");
for(i=1;i<=n;i++)
{
printf("\t%d",l[i]);
}
getch();
}
enter the number
5
8
6
2
4
45
entered list are as follows 8 6 2 4 45
HEAP 45 8 2 4 6
8 6 2 4 45
6 4 2 8 45
2 4 6 8 45
4 2 6 8 45
the sorted list 4 2 6 8 45
0 comments:
Post a Comment