111. Find Kth Smallest and Kth Largest Element

Back To All Submissions
Previous Submission
Next Submission

Code

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

void find_kth_elements(uint8_t *arr, uint8_t n, uint8_t k, uint8_t *smallest, uint8_t *largest) {
    // Your logic here
    for(int i = 0; i < (n - 1); i++){
        for(int j = i + 1; j < n; j++){
            if(arr[j] < arr[i]){
                int temp;
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    int kth_smallest_index = k - 1;
    int kth_largest_index = n - k;

    *smallest = arr[kth_smallest_index];
    *largest =  arr[kth_largest_index];
}

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

 

 

 

Was this helpful?
Upvote
Downvote