Find Kth Smallest and Kth Largest Element

Code

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

void sort_array(uint8_t *arr, uint8_t n) {
    for (uint8_t i = 0; i < n - 1; i++) {
        uint8_t min_idx = i;
        for (uint8_t j = i + 1; j < n; j++) {
            if (arr[j] < arr[min_idx]) {
                min_idx = j;
            }
        }
        // Swap arr[i] and arr[min_idx]
        uint8_t temp = arr[i];
        arr[i] = arr[min_idx];
        arr[min_idx] = temp;
    }
}

void find_kth_elements(uint8_t *arr, uint8_t n, uint8_t k, uint8_t *smallest, uint8_t *largest) {
    sort_array(arr, n);
    *smallest = arr[k - 1];     // k-th smallest
    *largest = arr[n - k];      // k-th 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;
}

Solving Approach

1.Sort the array in ascending order using selection sort.

2.Pick elements by index:

  • k-th smallest = arr[k - 1]
  • k-th largest = arr[n - k]

     

     

 

 

Upvote
Downvote
Loading...

Input

5 10 3 5 2 7 2

Expected Output

3 7