88. Find Top 3 Largest Values in an Array

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

// Sort array in descending order using bubble sort and print top 3
void find_top_3(uint8_t *arr, uint8_t n) {
    // Sort in descending order
    for (uint8_t i = 0; i < n - 1; i++) {
        for (uint8_t j = 0; j < n - i - 1; j++) {
            if (arr[j] < arr[j + 1]) {
                uint8_t temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    // Print top 3 values
    uint8_t limit = (n < 3) ? n : 3;
    for (uint8_t i = 0; i < limit; i++) {
        printf("%hhu", arr[i]);
        if(i < limit-1){
            printf(" ");
        }
    }
}

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;
}

What’s the goal?

Sort the array in descending order, and print the top 3 largest numbers.

Why it matters in firmware?

  • Useful in sensor signal filtering
  • Peak detection in input buffer
  • Rank highest values for threshold decisions
  • No need for full sorting or struct logic in simple numeric buffers

Solution Logic

  • Sort array in descending order using basic bubble sort
  • Print first 3 values
     
Loading...

Input

6 10 90 20 80 70 30

Expected Output

90 80 70