Find Kth Smallest and Kth Largest Element

Code

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

void sort_array(uint8_t *arr, uint8_t n) {
    for(int i = 1; i<n; i++)
    {
        int key = arr[i];
        int j = i-1;
        while(j >=0 && arr[j] > key)
        {
            arr[j+1] = arr[j];
            j--;
        }
        arr[j+1] = key;
    }
    
    // Sort in ascending order
}

void find_kth_elements(uint8_t *arr, uint8_t n, uint8_t k, uint8_t *smallest, uint8_t *largest) {
    sort_array(arr,n);
    if(n == k)
    {
        *smallest = arr[n-1];
        *largest = arr[0];

    }
    else
    {
        *smallest = arr[k-1];
        *largest = arr[n-k];
    }
    // Your logic here
}

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

 

 

 

Upvote
Downvote
Loading...

Input

5 10 3 5 2 7 2

Expected Output

3 7