0% found this document useful (0 votes)
7 views2 pages

Practical 13

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)
7 views2 pages

Practical 13

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/ 2

Practical 13.

Write a program to implement Heap sort


#include <stdio.h>

void heapify(int arr[], int n, int i) {


int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;

if (l < n && arr[l] > arr[largest])


largest = l;

if (r < n && arr[r] > arr[largest])


largest = r;

if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;

heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

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


int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;

heapify(arr, i, 0);
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int n;

printf("Enter the number of elements: ");


scanf("%d", &n);
int arr[n];

printf("Enter the elements:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);

printf("Jaspreet Singh(024)");

return 0;
}

You might also like