112. Find Top 3 Largest Values in an Array

Back To All Submissions
Previous Submission
Next Submission

Code

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

void selection_sort(uint8_t *arr, uint8_t n) {
    for (uint8_t i = 0; i < n - 1; i++) {
        uint8_t max_idx = i;  // 假設當前 i 是最大值
        for (uint8_t j = i + 1; j < n; j++) {
            if (arr[j] > arr[max_idx]) {
                max_idx = j;  // 更新最大值索引
            }
        }
        // 交換 arr[i] 與 arr[min_idx]
        uint8_t temp = arr[i];
        arr[i] = arr[max_idx];
        arr[max_idx] = temp;
    }
}

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

 

 

 

Was this helpful?
Upvote
Downvote