Find Top 3 Largest Values in an Array

Code

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

void find_top_3(uint8_t *arr, uint8_t n) {
    bool sorted = false;
    while(!sorted){
        sorted = true;
        uint8_t start=0,end=start+1;
        while(start<=n-2 || end<=n-1){
            if(arr[start]>arr[end]){
                uint8_t tmp=arr[start];
                arr[start]=arr[end];
                arr[end]=tmp;
                sorted=false;
            }
            start++,end++;
        }
    }
    uint8_t count=0;
    int8_t idxArr=n-1;
    while(idxArr>=0 && count<3){
        printf("%d",arr[idxArr]);
        printf(" ");
        idxArr--,count++;
    }
    
}

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