109. Sort an Array in Ascending Order

Back To All Submissions
Previous Submission
Next Submission

Code

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


void swap(uint8_t* p1, uint8_t* p2){
    uint8_t temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}
void bubble_sort(uint8_t *arr, uint8_t n) {
    // Your logic here
    int i,j;
    bool swapped;
    for(int i = 0; i< n-1;i++){
        swapped = 0;
        for(int j=0;j<n-i-1;j++){
            if(arr[j]>arr[j+1]){
                swap(&arr[j], &arr[j + 1]);
                swapped = true;
            }
        }

        // If no two elements were swapped by inner loop,
        // then break
        if (swapped == false)
            break;
        }
        

    }


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