Find Top 3 Largest Values in an Array

Code

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

void find_top_3(uint8_t *arr, uint8_t n) {
    // Your logic here
    uint8_t m1=0,m2=0,m3=0;
    for(int i=0;i<n;i++){
        uint8_t val= *(arr+i);
        if(val>m1){
            m3=m2;m2=m1;m1=val;
        }
        else if(val>m2){
            m3=m2;m2=val;
        }
        else if(val>m3) m3=val;
    }
    if(n>=1) printf("%hhu",m1);
    if(n>=2) printf(" %hhu",m2);
    if(n>=3) printf(" %hhu",m3);

}

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

 

 

 

Upvote
Downvote
Loading...

Input

6 10 90 20 80 70 30

Expected Output

90 80 70