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
    for (int i = 0 ; i < n - 1; i++){
        int max_index = i;
        for (int j = i + 1; j < n; j++ ){
            if (arr[j] > arr[max_index]){
                max_index = j;
            }
        }
        if (max_index != i){
            int temp = arr[i];
            arr[i] = arr[max_index];
            arr[max_index] = temp;
        }
    }

    int k = (n < 3) ? n : 3;
    for (int i = 0; i < k; i++){
        printf("%d",arr[i]);
        if (i < k - 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;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

6 10 90 20 80 70 30

Expected Output

90 80 70