#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void maxHeapify(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) {
swap(&arr[i], &arr[largest]); // swap root with largest child
maxHeapify(arr, n, largest); // recursively heapify affected subtree
}
}
void buildMaxHeap(int arr[], int n) {
// Build max heap from bottom up
for (int i = n / 2 - 1; i >= 0; i--) {
maxHeapify(arr, n, i); // heapify each non-leaf node
}
}
int extractMax(int arr[], int *n) {
if (*n <= 0) return -1; // empty heap
int max = arr[0]; // root is max
arr[0] = arr[*n - 1]; // move last element to root
(*n)--; // reduce heap size
maxHeapify(arr, *n, 0); // restore max heap
return max;
}
int kthLargest(int arr[], int n, int k) {
buildMaxHeap(arr, n); // step 1: build max heap
int size = n;
int maxVal = -1;
for (int i = 0; i < k; i++) {
maxVal = extractMax(arr, &size); // extract max k times
}
return maxVal; // kth largest
}
int main() {
int arr[] = {20, 10, 40, 30, 50, 25, 35};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
int result = kthLargest(arr, n, k);
printf("%d\n", result);
return 0;
}
build max heap so largest element is at root
maxVal = extractMax(arr, &size);
extract max element and reduce heap size
restore max heap property after extraction