Find Top 3 Largest Values in an Array

Code

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

void bubble_sort(uint8_t *arr, uint8_t n) {
    // Your logic here
    for(uint8_t i=n-1;i >=0; i--)
    {
        uint8_t didSwap = 0;
        for(uint8_t j = 0; j<= i-1;j++)
        {
            if(arr[j] > arr[j+1])
            {
                uint8_t temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
                didSwap = 1;
            }
        }
        if(!(didSwap)) break;
    }
}

void find_top_3(uint8_t *arr, uint8_t n) {
    // Your logic here
    if(n == 1)
    {
        printf("%d", arr[0]);
        return;
    }
    bubble_sort(arr,n);
    for(uint8_t i=0;i<3;i++)
    {
        if((n-1-i) >= 0)
        {
            printf("%d ",arr[(n-1-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;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

6 10 90 20 80 70 30

Expected Output

90 80 70