# Heap Sort – C Source Code and Algorithm

Heap sort is a relatively simple algorithm built upon the heap data structure. A naive implementation requires additional space, but it is possible to do a heap sort in place. Heap sort has guaranteed O(n*log(n))) performance, though the constant factor is typically a bit higher than for other algorithms such as Quick sort. Heap sort is not a stable sort, so the original ordering of equal elements may not be maintained.

The binary heap data structures is an array that can be viewed as a complete binary tree. Each node of the binary tree corresponds to an element of the array. The array is completely filled on all levels except possibly lowest.

### Properties of Heap Sort

• Not stable
• O(1) extra space
• O(n·lg(n)) time

### Algorithm of Heap Sort

```Heap_sort(A,n)

{

For i=n/2 down to 1

Heapify(A,i,n)

For i=n down to 2

{

swap(A[i],A[1])

Heapify(A,1,i-1)

}

}

Heapify(A,i,n)

{

Left=2*i;

Right= 2*i+1;

If(left<=n and right<=n) { if(A[left]>=A[right])

Max=left

Else

Max=right

If(A[max]>A[i])

{

Swap(A[max],A[i])

Heapify(A,max,n)

}

}

Else

If(left<=n) { If(A[left]>A[i])

Swap(A[left],A[i])\

}

}```

Heap sort is simple to implement, performs an O(n·lg(n)) in-place sort, but is not stable.

The first loop, the Θ(n) “heapify” phase, puts the array into heap order. The second loop, the O(n·lg(n)) “sortdown” phase, repeatedly extracts the maximum and restores heap order.

The sink function is written recursively for clarity. Thus, as shown, the code requires Θ(lg(n)) space for the recursive call stack. However, the tail recursion in sink() is easily converted to iteration, which yields the O(1) space bound.

Both phases are slightly adaptive, though not in any particularly useful manner. In the nearly sorted case, the heapify phase destroys the original order. In the reversed case, the heapify phase is as fast as possible since the array starts in heap order, but then the sortdown phase is typical. In the few unique keys case, there is some speedup but not as much as in shell sort or 3-way quicksort.

### Code of Heap Sort

```#include<stdio.h>

#include<conio.h>

int heap_size;

void heapsort(int a[],int n)

{

int i,temp;

build_heap(a,n);

for(i=n;i>=2;i–)

{

temp=a[1];

a[1]=a[i];

a[i]=temp;

heap_size–;

heapify(a,1);

}

}

build_heap(int a[],int n)

{

int i;

heap_size=n;

for(i=(n/2);i>=1;i–)

heapify(a,i);

}

heapify(int a[],int i)

{

int l,r,largest,temp;

l=2*i;

r=2*i+1;

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[largest];

a[largest]=a[i];

a[i]=temp;

heapify(a,largest);

}

}

void main()

{

int a[10];

int n,i;

clrscr();

printf(“enter the no of element”);

scanf(“%d”,&n);

printf(“enter the element”);

for(i=1;i<=n;i++)

{

scanf(“%d”,&a[i]);

}

heapsort(a,n);

printf(“The sorted list is:-“);

for(i=1;i<=n;i++)

{

printf(“%d”,a[i]);

}

getch();

}```