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
    int i,first=0,second=0,third=0,a;

    for(i=0;i<n;i++){
        if(arr[i]>first){
            third=second;
            second=first;
            first=arr[i];
        }
        else if(arr[i]>second){
            third=second;
            second=arr[i];
        }
        else if(arr[i]>third){
            third=arr[i];
        }
    }
    if(n>=3) a=3;
    else  a=n;
    if (a >= 1) printf("%hhu ", first);
    if (a >= 2) printf("%hhu ", second);
    if (a == 3) printf("%hhu", third);
}
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