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

Heap

Uploaded by

khushisingh7628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Heap

Uploaded by

khushisingh7628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

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

int largest =i; // Initialize largest as root


int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child
// If left child is larger than root
if (left < n && arr[left] > arr[largest])
largest = left;
// If right child is larger than largest so far
if (right < n && arr[right] > arr[largest])
largest = right;
// If largest is not root
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
// Recursively heapify the affected subtree
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 count,k;
printf("Enter [Link] elements:");
scanf("%d",&count);
int arr[count];
printf("Enter the elements of an array: ");
for (k=0;k<count;k++){
scanf("%d",&arr[k]);}
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
printf("Sorted array is \n");
printArray(arr, n);

}S

You might also like