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) {

    for(int i = 0; i < n-1; i++)
    {
        for(int j = 0; j < n-i-1; j++)
        {
            if(arr[j] > arr[j+1])
            {
                int temp = arr[j+1];
                arr[j+1] = arr[j];
                arr[j] = temp;
            }

        }
    }
    
}

//worst case time complexity - O(N2)
void insertion_sort(uint8_t *arr, uint8_t n)
{
    for(int i = 1; i < n; i++)
    {
        int temp = arr[i];
        int j = i - 1;
        while(j >= 0 && arr[j] > temp)
        {
            arr[j+1] = arr[j]; //shift element to right
            j--;
        }
        arr[j+1] = temp; //insert element

    }
}

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