86. Sort an Array in Descending Order

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

// Bubble sort: descending order
void bubble_sort_desc(uint8_t *arr, uint8_t n) {
    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]) {
                // Swap values
                uint8_t temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    uint8_t n;
    scanf("%hhu", &n);
    uint8_t arr[100];

    for (uint8_t i = 0; i < n; i++) {
        scanf("%hhu", &arr[i]);
    }

    bubble_sort_desc(arr, n);

    for (uint8_t i = 0; i < n; i++) {
        printf("%hhu", arr[i]);
        if(i < n-1){
            printf(" ");
        }
    }

    return 0;
}

What’s the goal?

Sort the array largest to smallest using bubble sort.

Why it matters in firmware?

  • Descending order is often needed in:
    • Signal ranking, top N values
    • Scheduling based on priority
    • Filtering highest sensor value (without using max() logic repeatedly)

Solution Logic

  • Same as bubble sort, but swap when arr[j] < arr[j+1]
  • Brings the largest value to front in each pass

     
Loading...

Input

5 10 3 5 2 7

Expected Output

10 7 5 3 2