All submissions

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 top[3] = {0, 0, 0};
    uint8_t count = 3;
    if (n < 3){
        count = n;
    }

    for (uint8_t i = 0; i < n; i++) {
        if (arr[i] > top[0]) {
            top[2] = top[1];
            top[1] = top[0];
            top[0] = arr[i];
        } 
        else if (arr[i] > top[1]) {
            top[2] = top[1];
            top[1] = arr[i];
        } 
        else if (arr[i] > top[2]) {
            top[2] = arr[i];
        }
    }
    for (uint8_t i = 0; i < count; i++) {
        printf("%d ", top[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;
}

 

 

 

Loading...

Input

6 10 90 20 80 70 30

Expected Output

90 80 70