Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views3 pages

Heap Sort

This C program implements a max heap data structure and sorts an array of integers. It includes functions to build a max heap and to heapify the array. The user is prompted to input the number of elements and the elements themselves, which are then sorted and displayed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Heap Sort

This C program implements a max heap data structure and sorts an array of integers. It includes functions to build a max heap and to heapify the array. The user is prompted to input the number of elements and the elements themselves, which are then sorted and displayed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

PROGRAM:

#include <stdio.h>

void heapify(int heap[], int n);

void build_maxheap(int heap[], int n);

void build_maxheap(int heap[], int n) {

int i, c, r, t;

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

c = i;

do {

r = (c - 1) / 2;

if (heap[r] < heap[c]) {

t = heap[r];

heap[r] = heap[c];

heap[c] = t;

c = r;

} while (c != 0);

printf("Unsorted heap array:\n");

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

printf("%d\n", heap[i]);

heapify(heap, n);

void heapify(int heap[], int n) {

int i, t, c, r;

for (i = n - 1; i >= 0; i--) {

t = heap[0];

heap[0] = heap[i];

heap[i] = t;

r = 0;

do {
c = (2 * r + 1);

if (c < (i - 1) && heap[c] < heap[c + 1])

c++;

if (c < i && heap[r] < heap[c]) {

t = heap[r];

heap[r] = heap[c];

heap[c] = t;

r = c;

} while (c < i);

int main() {

int n, i;

int heap[20];

printf("How many numbers are you going to enter?\n");

scanf("%d", &n);

printf("Enter %d elements:\n", n);

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

scanf("%d", &heap[i]);

build_maxheap(heap, n);

printf("Sorted heap array:\n");

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

printf("%d\n", heap[i]);

return 0;

}
OUTPUT:

You might also like