85. Sort an Array in Ascending Order

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

// Perform bubble sort on the array
void bubble_sort(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(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 an array using the classic bubble sort, a simple comparison-based sorting method.

Why it matters in firmware?

  • Though not efficient for large arrays, it’s:
    • Easy to implement and debug
    • Useful for small buffers (like UART queues, config arrays)
    • Often used where code clarity is more important than performance
  • Can be modified for descendingpartial, or stable sorts

Solution Logic

  • Repeatedly swap adjacent elements if they are in the wrong order
  • Outer loop controls the number of passes
  • Inner loop compares and swaps as needed

     
Loading...

Input

5 10 3 5 2 7

Expected Output

2 3 5 7 10