87. Find Kth Smallest and Kth Largest Element

#include <stdio.h>
#include <stdint.h>

// Sort array in ascending order (bubble sort)
void sort_array(uint8_t *arr, uint8_t n) {
    for (uint8_t i = 0; i < n - 1; i++) {
        for (uint8_t j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                uint8_t temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

// Find kth smallest and kth largest
void find_kth_elements(uint8_t *arr, uint8_t n, uint8_t k, uint8_t *smallest, uint8_t *largest) {
    sort_array(arr, n);  // Sort the array

    *smallest = arr[k - 1];         // (k-1)th index → kth smallest
    *largest = arr[n - k];          // (n-k)th index → kth largest
}

int main() {
    uint8_t n, k;
    scanf("%hhu", &n);
    uint8_t arr[100];

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

    scanf("%hhu", &k);

    uint8_t smallest, largest;
    find_kth_elements(arr, n, k, &smallest, &largest);

    printf("%hhu %hhu", smallest, largest);
    return 0;
}

What’s the goal?

After sorting, pick the k-1 index for kth smallest, and n-k index for kth largest.

Why it matters in firmware?

  • Find mid/max/threshold values in buffers (e.g., temperature ranking)
  • Peak detection in waveform processing
  • Prioritizing buffer elements without full sort in real time

Solution Logic

  • Use bubble sort to arrange in ascending order
  • Select values based on indexed position: arr[k-1] and arr[n-k]
     
Loading...

Input

5 10 3 5 2 7 2

Expected Output

3 7