Thursday 15 August 2019

C program for sorting- ascending order, descending order


/*sorting in an ascending order */
#include<stdio.h>
void
main()
{
                int i,j,n;
                float a[100],t;
                printf("enter the total number of data:");
                scanf("%d",&n);
                printf("enter  the data :\n");
                for(i=0;i<n;i++)
                scanf("%f",&a[i]);
                for(i=0;i<(n-1);i++)
                {
                                for(j=i+1;j<n;j++)
                                {
                                                if(a[i]>a[j])
                                                {
                                                                t=a[i];
                                                                a[i]=a[j];
                                                                a[j]=t;
                                                }
                                }
                }
                printf("\n sorted array in ascending is :\n");
                for(i=0;i<n;i++)
                                printf("%f \n",a[i]);
}
Result:
enter the total number of data:8
enter the data :
78
90
4
3
78
23
1
0

 sorted array in ascending is :
0.000000
1.000000
3.000000
4.000000
23.000000
78.000000
78.000000
90.000000
Press any key to continue



/*sorting in an descending order */
#include<stdio.h>
void
main()
{
                int i,j,n;
                float a[100],t;
                printf("enter the total number of data:");
                scanf("%d",&n);
                printf("enter the data :\n");
                for(i=0;i<n;i++)
                scanf("%f",&a[i]);
                for(i=0;i<n;i++)
                {
                                for(j=i+1;j<=n;j++)
                                {
                                                if(a[i]<a[j])
                                                {
                                                                t=a[i];
                                                                a[i]=a[j];
                                                                a[j]=t;
                                                }
                                }
                }
                printf("\n sorted array in descending is :\n");
                for(i=0;i<n;i++)
                                printf("%f \n",a[i]);
}
Result:
enter the total number of data:10
enter the data :
56
7
9
87
67
57
19
21
66
71
 sorted array in descending is :
87.000000
71.000000
67.000000
66.000000
57.000000
56.000000
21.000000
19.000000
9.000000
7.000000
Press any key to continue

No comments:

Post a Comment

Thanks for comment.