Find Kth Smallest and Kth Largest Element

Code

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

void merge(uint8_t *arr, int l,int m,int h)
{
       int n1 = m - l + 1;
    int n2 = h - m;

    uint8_t left[n1], right[n2];

    // Copy data to temp arrays
    for(int i = 0; i < n1; i++) left[i] = arr[l + i];
    for(int j = 0; j < n2; j++) right[j] = arr[m + 1 + j];

    int i = 0, j = 0, k = l;

    // Merge back to arr
    while(i < n1 && j < n2){
        if(left[i] <= right[j]) arr[k++] = left[i++];
        else arr[k++] = right[j++];
    }

    while(i < n1) arr[k++] = left[i++];
    while(j < n2) arr[k++] = right[j++];
}
void merge_sort_helper(uint8_t *arr, int l,int h){
    if(l>=h) return;
    int mid = l+(h-l)/2;
    merge_sort_helper(arr,l,mid);
    merge_sort_helper(arr,mid+1,h);
    merge(arr,l,mid,h);
}
void sort_array(uint8_t *arr, uint8_t n) {
    // Sort in ascending order
    merge_sort_helper(arr,0,n-1);
}

void find_kth_elements(uint8_t *arr, uint8_t n, uint8_t k, uint8_t *smallest, uint8_t *largest) {
    // Your logic here
    sort_array(arr,n);
    smallest[0]= arr[k-1];
    largest[0]=arr[n-k];
}

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