#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int arr[], int n, int i) {
int smallest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] < arr[smallest])
smallest = left;
if (right < n && arr[right] < arr[smallest])
smallest = right;
if (smallest != i) {
swap(&arr[i], &arr[smallest]);
heapify(arr, n, smallest); // heapify subtree
}
}
int extractMin(int arr[], int *n) {
if (*n <= 0) return -1; // empty heap
int root = arr[0];
arr[0] = arr[*n - 1];
(*n)--;
heapify(arr, *n, 0); // restore heap property
return root;
}
void buildMinHeap(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i); // build heap from bottom up
}
}
int kthSmallest(int arr[], int n, int k) {
buildMinHeap(arr, n); // step 1: build min heap
int result = -1;
for (int i = 0; i < k; i++) {
result = extractMin(arr, &n); // extract min k times
}
return result;
}
int main() {
int arr[] = {7, 10, 4, 3, 20, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
int result = kthSmallest(arr, n, k);
printf("%dth smallest element is %d\n", k, result);
return 0;
}
build min heap so smallest element is at root
result = extractMin(arr, &n);
extract min element k times to reach kth smallest
restore heap property after removing root
3th smallest element is 7