All submissions

Find Kth Smallest and Kth Largest Element

Code

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

int helper_function(const void *a,const void *b)
{
    uint8_t num1=*((int *)a);
    uint8_t num2=*((int *)b);

    return num1>num2;
}

void sort_array(uint8_t *a, uint8_t n) 
{
    qsort(a,n,sizeof(char),helper_function);
}

void find_kth_elements(uint8_t *a, uint8_t n, uint8_t k, uint8_t *smallest, uint8_t *largest) 
{
    sort_array(a,n);
    *smallest=a[k-1];
    *largest=a[n-k]; //n-1-(k-1) -> n-1-k+1--> n-k
}
//2 3 5 7 10 k=2
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