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) {
    uint8_t first = 0;
    uint8_t sec = 0;
    uint8_t third = 0;

    for (uint8_t i = 0; i < n; i++) {
        if (arr[i] > first) {
            third = sec;
            sec = first;
            first = arr[i];
        } else if (arr[i] > sec) {
            third = sec;
            sec = arr[i];
        } else if (arr[i] > third) {
            third = arr[i];
        }
    }

    // Số phần tử thực tế muốn in
    uint8_t cnt = (n < 3) ? n : 3;

    // In ra top 3 (hoặc <3 nếu n<3)
    for (uint8_t i = 0; i < cnt; i++) {
        if (i == 0) printf("%hhu", first);
        else if (i == 1) printf(" %hhu", sec);
        else if (i == 2) printf(" %hhu", third);
    }
    printf("\n");
}

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