All submissions

Sort an Array in Ascending Order

Code

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

int helper_function(const void *a,const void *b)
{
    uint8_t num1 = *((uint8_t *)a);  // Cast to uint8_t and dereference
    uint8_t num2 = *((uint8_t *)b);  // Cast to uint8_t and dereference

    return num1>num2;
}
void bubble_sort(uint8_t *a, uint8_t n) 
{
    int sort_flag=0;
    int i=1;
    int j=0;
    
    do
    {
        for(j=0;j<n-1;j++)
        {
            if(a[j]>a[j+1])
            {
                int temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
                sort_flag=1;
            }
        }

        i++; //when the array is already sorted,sort_flag remains zero we donot need to perform extra inner loop.
    }while(sort_flag && (i<n));
}

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