Wednesday, December 4, 2019

Write a program in C to sort elements of array in ascending order.

#include<stdio.h>

void main()
{
    int arr1[100];
    int n, i, j, tmp;
      
      
       printf("\n\nsort elements of array in ascending order :\n ");
       printf("----------------------------------------------\n");    

    printf("Input the size of array : ");
    scanf("%d", &n);

       printf("Input %d elements in the array :\n",n);
       for(i=0;i<n;i++)
            {
              printf("element - %d : ",i);
              scanf("%d",&arr1[i]);
            }

    for(i=0; i<n; i++)
    {
        for(j=i+1; j<n; j++)
        {
          //big or small ele comparision & ordering them          
        if(arr1[j] <arr1[i])
            {
                tmp = arr1[i];
                arr1[i] = arr1[j];
                arr1[j] = tmp;
            }
        }
    }
    printf("\nElements of array in sorted ascending order:\n");
    for(i=0; i<n; i++)
    {
        printf("%d  ", arr1[i]);
    }
                printf("\n\n");
}

/*
sort elements of array in ascending order :
 ----------------------------------------------
Input the size of array : 6
Input 6 elements in the array :
element - 0 : 9
element - 1 : 3
element - 2 : 8
element - 3 : 2
element - 4 : 7
element - 5 : 4

Elements of array in sorted ascending order:
2  3  4  7  8  9
*/

No comments:

Post a Comment