112. Find Top 3 Largest Values in an Array

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int cmp (const void* a, const void* b){
    uint8_t x = *(uint8_t*)a;
    uint8_t y = *(uint8_t*)b;
    return (x>y) - (y>x);
}
void find_top_3(uint8_t *arr, uint8_t n) {
    // Your logic here
    qsort(arr, n, sizeof(uint8_t), cmp);
    int i = n - 1;
    while(i >= 0 && i > (n-4)){
        printf("%d ", arr[i]);
        i--;
    }
}

int main() {
    uint8_t n;
    scanf("%hhu", &n);
    uint8_t arr[100];

    for (uint8_t i = 0; i < n; i++) {
        scanf("%hhu", &arr[i]);
    }

    find_top_3(arr, n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote