All submissions

Sort an Array in Ascending Order

Code

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

void swap(uint8_t *a, uint8_t *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

void bubble_sort(uint8_t *arr, uint8_t n) {
#define SELECTION_SORT
#ifdef SELECTION_SORT
    for (uint8_t i = 0; i < n - 1; i++) {
        uint8_t min_idx = i;
        for (uint8_t j = i+1; j < n; j++) {
            if (arr[j] < arr[min_idx]) {
                min_idx = j;
            }
        }
        if (min_idx != i)
            swap(&arr[min_idx], &arr[i]);
    }
#endif

#ifdef BUBBLE_SORT
    for (uint8_t i = 0; i < n - 1; i++) {
        for (uint8_t j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j+1]) {
                swap(&arr[j], &arr[j+1]);
            }
        }
    }
#endif

#ifdef INSERTION_SORT
    // insertion sort
    for (uint8_t i = 1; i < n; i++) {
        int j = i - 1;
        int key = arr[i];
        while (j >= 0 && arr[j] > key) {
            arr[j+1] = arr[j];
            j--;
        }
        arr[j+1] = key;
    }
#endif
}

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;
}

Solving Approach

 

 

 

Loading...

Input

5 10 3 5 2 7

Expected Output

2 3 5 7 10