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) {
    int first = -1, second = -1, third = -1;

    for (int i = 0; i < n; i++) {
        int val = arr[i];

        if (val > first) {
            third = second;
            second = first;
            first = val;
        }
        else if (val > second) {
            third = second;
            second = val;
        }
        else if (val > third) {
            third = val;
        }
    }

    if (n >= 1) printf("%d ", first);
    if (n >= 2) printf("%d ", second);
    if (n >= 3) printf("%d ", 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