109. Sort an Array in Ascending Order

Back To All Submissions
Previous Submission
Next Submission

Code

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

void bubble_sort(uint8_t *arr, uint8_t n) {
    // Your logic here
    // 1. Compare the previous value to current value
    // 2. If prev val > current value
    // 3. Copy prev val into temp, cur into prev, temp into current
    // 4. Repeat until end
    uint8_t temp;
    for(int i=0;i<n-1;i++){
        for(int j=i+1;j<n;j++){
            if(arr[i] > arr[j]){ //If prev value > cur val (push it up / swap them)
                temp = arr[j];
                arr[j] = arr[i];
                arr[i] = 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;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote