Heap Sort Using C Programming Language

How to write a C Program Heap Sort Using C Programming Language ?

sorting algorithm that works by first organizing the data to be sorted into a special type of binary tree called a heap. The heap itself has, by definition, the largest value at the top of the tree, so the heap sort algorithm must also reverse the order.

A complete binary tree is a binary tree in which each non-leaf has two children and all the leaves are at the same depth from the root.

A nearly complete binary tree is a binary tree constructed from a complete binary tree by eliminating a number of nodes (possibly none) from right at the leaf level.

A heap is a node-labeled, nearly complete binary tree with a special property.

The (Binary) heap data structure is an array object that can be

viewed as a nearly complete binary tree.

See More : Heapsort

Solution For C Program :




//HEAP SORT C PROGRAM

#include<stdio.h>
main()
{
     int a[25],n,i;
     system("clear");
     printf("enter the size of the array\n");
     scanf("%d",&n);
     printf("enter %d elements into the array\n",n);
     for(i=0;i<n;i++)
     {
 scanf("%d",&a[i]);
 heap(a,i,a[i]);
     }
     heapsort(a,n);
     printf("sorted elements are\n");
     for(i=0;i<n;i++)
     {
 printf("%d ",a[i]);
     }
}
heap(int a[],int pos,int k)
{
     int f;
     f=(pos-1)/2;
     while(pos>0 && k>a[f])
     {
 a[pos]=a[f];
 pos=f;
 f=(pos-1)/2;
     }
     a[pos]=k;
}
heapsort(int a[],int n)
{
     int k,key,i,j;
     for(i=n-1;i>0;i--)
     {
 key=a[0];
 a[0]=a[i];
 a[i]=key;
 for(j=0;j<i;j++)
 {
     heap(a,j,a[j]);
 }
     }
}

The height of a node is the maximum number of downward edges to a leaf node.

C Program's related to How to Heap Sort Using C Programming Language :

1. How to Write a c program for bubble sort algorithm.
2. How to Write a c program for insertion sort algorithm.
3. How to Write a c program for selection sort algorithm.
4. How to Write a c program for quick sort algorithm.
5. How to Write a c program for heap sort algorithm.
6. How to Write a c program for merge sort algorithm.
7. How to Write a c program for shell sort algorithm.


Learn More :