Heap Sort
#include
void insert_heap();
void build_heap();
void heap_sort();
main()
{
int k,N,*B;
printf("Enter the number of integers to be sorted:\n");
scanf("%d",&N);
B = (int *)malloc((N+1)*sizeof(int));
printf("Enter %d integers:\n",N);
for (k = 1; k <= N; k++)
scanf("%d",&B[k]);
heap_sort(B,N);
printf("The sorted array is:\n");
printf("\n");
for (k=1; k <= N; k++)
printf("B[%d] = %d\n",k,B[k]);
printf("\n");
return 0;
} /* main */
void insert_heap(int *A, int root, int last)
{
/*
* pre: The array A contains entries of type integer.
* post: The entries of A between indices root and last
* have been exchanged when needed to form a partial heap.
*/
int lchild, rchild, nextroot, temp;
lchild = 2*root; /* lchild now left child of root */
rchild = lchild + 1; /* rchild now right child of root */
nextroot = root;
/*
* lchild or rchild becomes next root, depending on which
* has a larger entry.
*/
if (lchild <= last && A[root] < A[lchild])
nextroot = lchild;
if (rchild <= last && A[nextroot] < A[rchild])
nextroot = rchild;
if (nextroot > root)
{ /* swap entries at root and nextroot */
temp = A[root];
A[root] = A[nextroot];
A[nextroot] = temp;
insert_heap(A,nextroot,last);
}
} /* insert_heap */
void build_heap(int *A, int n)
{
/*
* pre: The array A has entries of integer type.
* post: The entries of A have been rearranged so that
* A becomes a heap.
*/
int root; /* All entries beyond root form a partial heap */
for (root = n/2; root >= 1; root--)
insert_heap(A,root,n);
} /* build_heap */
void heap_sort(int *A, int n)
{
/*
* pre: The array A contains entries of integer type.
* post: The entries of A have been rearranged so that they
* are sorted into non-decreasing order.
*/
int temp; /* temporary storage for moving entries */
int last; /* entries past last have been sorted */
build_heap(A,n);
for (last = n; last >= 2; last--)
{ /* swap first and last entries */
temp = A[1];
A[1] = A[last];
A[last] = temp;
insert_heap(A,1,last-1); /* restore heap properties */
}
} /* heap_sort */