All submissions

Find Kth Smallest and Kth Largest Element

Code

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

void swap(uint8_t *a, uint8_t *b) {
    uint8_t temp = *a;
    *a = *b;
    *b = temp;
}

void sort_array(uint8_t *arr, uint8_t n) {
    bool swapped;
    for (int i = 0; i < n - 1; i++) {
        swapped = false;
        for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(&arr[j], &arr[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

void find_kth_elements(uint8_t *arr, uint8_t n, uint8_t k, uint8_t *smallest, uint8_t *largest) {
    sort_array(arr, n);

    // Find k-th smallest unique
    uint8_t count = 1, i = 0;
    while (i < n - 1 && count < k) {
        if (arr[i] != arr[i + 1]) count++;
        i++;
    }
    *smallest = arr[i];

    // Find k-th largest unique
    count = 1;
    i = n - 1;
    while (i > 0 && count < k) {
        if (arr[i] != arr[i - 1]) count++;
        i--;
    }
    *largest = arr[i];
}

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

 

 

 

Loading...

Input

5 10 3 5 2 7 2

Expected Output

3 7