Home C Language Basic C Programs Sorting in C

Sorting in C

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

#include <stdio.h>

int main()

{

   int a[100],i,j,n,temp;

   printf(“Enter no.of elements: “);

   scanf(“%d”,&n);

   printf(“Enter elements in to the array:\n”);

   for(i=0;i<n;i++)

   scanf(“%d”,&a[i]);

   for(i=0;i<n-1;i++)

   {

      for(j=0;j<n-1;j++)

      {

         if(a[j]>a[j+1])

         {

            temp=a[j];

            a[j]=a[j+1];

            a[j+1]=temp;

         }

      }

   }

   printf(“Ascending order is:\n”);

   for(i=0;i<n;i++)

      printf(“%d\t”,a[i]);

}

Output:

Enter no.of elements: 6

Enter elements in to the array:

996         52           63           48           169         255

Ascending order is:

48           52           63           169         225         996