#include <stdio.h>
#include <stdlib.h>
// Function to heapify a subtree with root at given index
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child index
int right = 2 * i + 2; // Right child index
// 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 sub-tree
heapify(arr, n, largest);
}
}
// Function to perform Heap Sort
void heapSort(int arr[], int n) {
// Build a max heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// Extract elements from heap one by one
for (int i = n - 1; i > 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
// Function to print the array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int n;
// Accepting user input for array size
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Generating random array elements
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Sorting using Heap Sort
heapSort(arr, n);
// Printing the sorted array
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCi8vIEZ1bmN0aW9uIHRvIGhlYXBpZnkgYSBzdWJ0cmVlIHdpdGggcm9vdCBhdCBnaXZlbiBpbmRleAp2b2lkIGhlYXBpZnkoaW50IGFycltdLCBpbnQgbiwgaW50IGkpIHsKICAgIGludCBsYXJnZXN0ID0gaTsgICAgICAgLy8gSW5pdGlhbGl6ZSBsYXJnZXN0IGFzIHJvb3QKICAgIGludCBsZWZ0ID0gMiAqIGkgKyAxOyAgLy8gTGVmdCBjaGlsZCBpbmRleAogICAgaW50IHJpZ2h0ID0gMiAqIGkgKyA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Zm9yZ2Vla3MKZ2Vla3Nmb3JnZWVrcwpnZWVrc2ZvcmdlZWtz
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks